Mybatis mybatis – MyBatis 3 | 中文文档
<dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis</artifactId > <version > 3.5.6</version > </dependency >
持久层 持久化 数据持久化
持久化就是将程序的数据在持久状态和瞬时状态转化的过程
数据库(jdbc),io文件持久化
持久层 Dao层,Service层,Controller层…
常用注解 @Alias("指定别名") @Select(" SQL ") @Param("映射的基本类型参数名称") 参数 @Data @SuppressWarnings("all")
配置 依赖
<dependencies > <dependency > <groupId > mysql</groupId > <artifactId > mysql-connector-java</artifactId > <version > 5.1.44</version > </dependency > <dependency > <groupId > org.mybatis</groupId > <artifactId > mybatis</artifactId > <version > 3.5.6</version > </dependency > </dependencies >
资源导出
找不到mapper文件:maven中存在资源过滤,target包中没有mapper配置文件。
解决方法:①拷贝mapper文件到target对应的软件包中
②maven由于他的约定大于配置,我们之后可以能遇到我们写的配置文件,无法被导出或者生效的问题,解决方案;
<build > <resources > <resource > <directory > src/main/resources</directory > <includes > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > true</filtering > </resource > <resource > <directory > src/main/java</directory > <includes > <include > **/*.properties</include > <include > **/*.xml</include > </includes > <filtering > true</filtering > </resource > </resources > </build >
核心配置文件
resources
driver =com.mysql.jdbc.Driver url =jdbc:mysql://localhost:3306/数据库?useSSL=false&useUnicode=true&characterEncoding=UTF-8 username =root password =123456 jdbc.driver =com.mysql.jdbc.Driver jdbc.url =jdbc:mysql://localhost:3306/数据库?useSSL=false&useUnicode=true&characterEncoding=utf8 jdbc.username =root jdbc.password =123456
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration > <properties resource ="db.properties" > </properties > <typeAliases > </typeAliases > <environments default ="development" > <environment id ="development" > <transactionManager type ="JDBC" /> <dataSource type ="POOLED" > <property name ="driver" value ="${driver}" /> <property name ="url" value ="${url}" /> <property name ="username" value ="${username}" /> <property name ="password" value ="${password}" /> </dataSource > </environment > </environments > <mappers > </mappers > </configuration >
Mapper.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace =" packName " > </mapper >
第一个Mybatis程序 创建子模块
配置文件 mybatis-config.xml
2.编写mybatis工具类(utils)
public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { String resource = "mybatis-config.xml" ; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder ().build(inputStream); }catch (IOException e){ e.printStackTrace(); } } public static SqlSession getSqlSession () { return sqlSessionFactory.openSession(); } }
3.编写代码
public interface UserDao { List<User>getUserList(); }
接口实现类 – 由原来的UserDaoImpl类变成一个Mapper配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace ="com.chen.dao.UserDao" > <select id ="getUserList" resultType ="com.chen.pojo.User" > select * from mybatisb.user </select > </mapper >
@Test public void test () { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao userdao=sqlSession.getMapper(UserDao.class); List<User> userList = userdao.getUserList(); for (User user : userList) {System.out.println(user);} sqlSession.close(); }
CRUD
SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userdao=sqlSession.getMapper(UserMapper.class); sqlSession.close();
1、namespace namespace中的包名要和Dao/mapper接口的包名一致!
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace ="com.chen.dao.UserMapper" > </mapper >
2、select 选择,查询语句:
List<User>getUserList(); User getUserById (int id) ;
<select id ="getUserList" resultType ="com.chen.pojo.User" > select * from mybatisb.user </select > <select id ="getUserById" parameterType ="int" resultType ="com.chen.pojo.User" > select * from mybatis.user where id = #{id} </select >
List<User> userList = userdao.getUserList(); User user = mapper.getUserById(1 );
模糊查询
List<User>getUserLike(String value);
<select id ="getUserLike" resultType ="com.chen.pojo.User" > select * from mybatisb.user where name like #{value} select * from mybatisb.user where name like "%"#{value}"%" </select >
List<User> userList=mapper.getUserLike("%陈%" ); List<User> userList=mapper.getUserLike("陈" );
通配符
模糊查询
1、Java代码执行的时候,传递通配符 %%
List<User> userList=mapper.getUserLike("%陈%" );
2、在sql拼接中使用通配符
<select id ="getUserLike" resultType ="com.chen.pojo.User" > select * from mybatisb.user where name like "%"#{value}"%" </select >
3、insert
增删改需要提交事务:sqlSession.commit();
插入语句:
<!--对象中的属性,可以直接取出来--> <insert id="addUser" parameterType="com.chen.pojo.User" > insert into mybatisb.user (id,name,pwd) values(#{id},#{name},#{pwd}); </insert>
int res = mapper.addUser(new User (9 ,"chen" ,"9999" ));sqlSession.commit();
4、update
增删改需要提交事务:sqlSession.commit();
更新语句:
int updateUser (User user) ;
<update id ="updateUser" parameterType ="com.chen.pojo.User" > update mybatisb.user set name=#{name},pwd=#{pwd} where id=#{id} </update >
mapper.updateUser(new User (1 , "cccccccc" , "222222222" )); sqlSession.commit();
5、delete
增删改需要提交事务:sqlSession.commit();
删除语句:
<delete id ="deleteUser" parameterType ="int" > delete from mybatisb.user where id=#{id} </delete >
mapper.deleteUser(9 ); sqlSession.commit();
注意点
增删改需要提交事务:sqlSession.commit();
5、万能Map
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Mp!
Map传递参数,直接在sql中取出key即可!【parameterType=”map”】对象传递参数,直接在sql中取对象的属性即可!【parameterType=”Object”】只有一个基本类型参数的情况下,可以直接在sq中取到!多个参数用Map ,或者注解 !
局部数据操作,不用操作数据表里面的全部数据(比如插入,可以为空的字段我不传值)
Map<String,Object>
第一个类型(String)不用变,可理解为键的名称必定为String
第二个类型(Object、String、Integer。。。),看需求传递的是纯单一类型的数据则选择该类型,对类型选择对象
int addUser2 (Map<String, Object> map) ;User getUserById2 (Map<String,Object> map) ;
<insert id ="addUser2" parameterType ="map" > insert into mybatisb.user (id,pwd) values(#{userId},#{passWord}); </insert > <select id ="getUserById2" parameterType ="map" resultType ="com.chen.pojo.User" > select * from mybatisb.user where id = #{id} and name = #{name} </select >
Map<String, Object> map = new HashMap <String, Object>(); map.put("userId" ,5 ); map.put("password" ,"99999222222" ); mapper.addUser2(map); HashMap<String, Object> map = new HashMap <>(); map.put("id" ,1 ); User user= mapper.getUserById2(map);
配置解析 1、核心配置文件
2、环境配置(environments)
Mybats 默认管理器是:JDBC,默认连接池:POOLED
<environments default ="development" > <environment id ="development" > <transactionManager type ="JDBC" /> <dataSource type ="POOLED" > <property /> </dataSource > </environment > <environment id ="test" > </environment > </environments >
3、属性优化(properties)
driver =com.mysql.jdbc.Driver url =jdbc:mysql://localhost:3306/数据库?useSSL=false&useUnicode=true&characterEncoding=UTF-8 username =root password =123456
2、引入外部配置文件(mybatis-config.xml)
<configuration > <properties resource ="db.properties" > <property name ="username" value ="root" /> <property name ="password" value ="123456" /> </properties > <environments default ="development" > <environment id ="development" > <transactionManager type ="JDBC" /> <dataSource type ="POOLED" > <property name ="driver" value ="${driver}" /> <property name ="url" value ="${url}" /> <property name ="username" value ="${username}" /> <property name ="password" value ="${password}" /> </dataSource > </environment > </environments > </configuration >
在核心配置文件中映入
<properties resource ="db.properties" > <property name ="username" value ="root" /> <property name ="password" value ="123456" /> </properties >
可以直接引入外部文件
可以在其中直接一些属性配置
如果两个文件有同一个字段,优先使用外部配置文件的
4、类型别名优化(typeAliases)
mybatis-config.xml
第一种:一个类起一个别名(实体类比较少推荐使用)
<typeAliases > <typeAlias type ="com.chen.pojo.User" alias ="User" /> </typeAliases >
第二种:指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean(实体类比较多推荐使用)
扫描实体类的包。它的默认 别名为这个类的别名,首字母小写
<typeAliases > <package name ="com.chen.pojo" /> </typeAliases >
<select id ="getUserList" resultType ="user" > select * from mybatisb.user </select >
5、设置(settings)
<settings > <setting name ="cacheEnabled" value ="true" /> <setting name ="lazyLoadingEnabled" value ="true" /> <setting name ="logImpl" value ="STDOUT_LOGGING" /> </settings >
6、其他 plugins 插件
mybatis-generator-core
mybatis-plus
7、映射器(mappers)
每一个Mapper.xml都需要在Mybatis核心配置文件中注册
<mappers > <mapper resource ="com/chen/dao/UserMapper.xml" /> <mapper class ="com.chen.dao.UserMapper" /> <package name ="com.chen.dao" /> </mappers >
方式一:resource (推荐使用)
<mappers > <mapper resource ="com/chen/dao/UserMapper.xml" /> </mappers >
方式二:使用class文件绑定注册
<mappers > <mapper class ="com.chen.dao.UserMapper" /> </mappers >
注意点
接口和它的Mapper配置文件必须同名
接口和它的Mapper配置文件必须在同一个包下
方式三:使用扫描包进行注入绑定
<package name ="com.chen.dao" />
8、生命周期和作用域
生命周期,和作用域,是至关重业的,因为错误的使用会导致非常严重的并发问题 。
SqlSessionFactory :
一旦创建了SqlSessionFactory,就不再需要它了
局部变量
SqlSessionFactory :
·说白了就是可以想象为:数据库连接池
SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例 。
·因此SqlSessionFactory的最佳作用域是应用作用域。
·最简单的就是使用单例模式 或者静态单例模式。
SqlSession
连接到连接池的一个请求!
SqlSession的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
·用完之后需要赶紧关闭,否则资源被占用!
解决属性名和表字段名不一致的问题
select * from mybatisb.user where id = #{id}select id,name,pwd from mybatisb.user where id = #{id}
解决方法
起别名 (字段名 as 属性名 (pwd as password))
< select id= "getUserById" parameterType= "int" resultType= "User"> select id,name,pwd as password from mybatisb.user where id = #{id} < / select >
resultMap 结果集映射
<resultMap id ="UserMap" type ="User" > <result column ="pwd" property ="password" /> </resultMap > <select id ="getUserById" resultMap ="UserMap" > select * from mybatisb.user where id = #{id} </select >
日志 标准日志工厂 如果一个数超库操作,出现了异常,我们需要排错。日志就是最好的助手 曾经:sout、debug 现在:日志工厂
<settings > <setting name ="logImpl" value ="STDOUT_LOGGING" /> </settings >
LOG4J(3.5.9 起废弃)
L0g4是APch的一个升派项日,通过使用L0g4,我们可以控制日志信息输送的目的地是控制台、文件、GU组件
我们也可以控制每一条日志的输出格式
过定义每一条日志信息的级别,我门能修更加细致地控制日志的生成过程
通过一个配置文生来灵活地进行配骨,而不需要修改应用的代码
1、导包
<dependency > <groupId > log4j</groupId > <artifactId > log4j</artifactId > <version > 1.2.17</version > </dependency >
2、log4j.properties
log4j.rootLogger =DEBUG,console,file log4j.appender.console org.apache.log4j.ConsoleAppender log4j.appender.console.Target System.out log4j.appender.console.Threshold =DEBUG log4j.appender.console.layout org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern =[%c]-%m%n log4j.appender.file org.apache.log4j.RollingFileAppender log4j.appender.file.File =./log/chen.log log4j.appender.file.MaxFilesize =10mb log4j.appender.file.Threshold =DEBUG log4j.appender.file.layout =org.apache.log4j.PatternLayout 1og4j.appender.file.layout.ConversionPattern =[%p][%d{yy-MM-dd}][%c]%m%n 1og4j.logger.org.mybatis =DEBUG log4j.logger.java.sql =DEBUG log4j.logger.java.sql.Statement =DEBUG log4j.logger.java.sql.ResultSet =DEBUG log4j.logger.java.sql.Preparedstatement =DEBUG
3、配置log4j为日志的实现
<settings > <setting name ="logImpl" value ="LOG4J" /> </settings >
4、Log4j的使用
在要使用Log4j的类中,导入包 import org.apache.log4j.Logger;
日志对象,参数为当前类的class
static->提升作用域
static Logger logger= Logger.getLogger(UserDaoTest.class);
logger.info("info:进入了testLog4j方法" ); logger.debug("info:进入了testLog4j方法" ); logger.error("info:进入了testLog4j方法" );
使用limit分页 SQL语法
select * from mybatisb.user limit x / / [0 ,x]select * from mybatisb.user limit startIndex,pageSize
1、接口
List<User> getUserByLimit (Map<String,Integer> map) ;
2、Mapper.xml
<resultMap id ="UserMap" type ="User" > <result column ="id" property ="id" /> <result column ="name" property ="name" /> <result column ="pwd" property ="password" /> </resultMap > <select id ="getUserByLimit" parameterType ="map" resultMap ="UserMap" > select * from mybatisb.user limit #{startIndex},#{pageSize} </select >
3、test
SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);HashMap<String, Integer> map = new HashMap <String, Integer>(); map.put("startIndex" ,0 ); map.put("pageSize" ,5 ); List<User> userList=mapper.getUserByLimit(map); for (User user : userList) { System.out.println(user); } sqlSession.close();
注解开发
结果集数据无法映射属性
本质:反射机制实现 底层:动态代理!
1、注解在接口上实现
@Select("select * from user") List<User> getUsers () ;
2、配置文件绑定接口
<mappers > <mapper class ="com.chen.dao.UserMapper" > </mapper > </mappers >
CRUD 1.查询
方法存在多个参数,所有的参数前面必须加上:**@Param(‘id’)** – SQL语句获取值的key
@Select("select * from user") List<User> getUsers () ; @Select("select * from user where id=#{id} and name=#{namec}") User getUserById (@Param("id") int id,@Param("namec") String name) ;
2.插入
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})") int addUser (User user) ;
3.更新
@Update("update user set name=#{name},pwd=#{password} where id=#{id}") int Upadatec (User user) ;
4.删除
@Delete("delete from user where id=#{id}") int delete (@Param("id") int id) ;
关于@Param()注解
基本类型的参数或者String:类型,需要加上
引用类型不需要加–对象
如果只有一个基本类型的话,可以忽略,但是建议大家都劭加上!
我们在SQL中引用的就是我们这里的@Param()中设定的属性 名!
Lombok 使用 :(自动生成get和set方法)
使用注解后点击编译器左边的看结构
导包
<dependency > <groupId > org.projectlombok</groupId > <artifactId > lombok</artifactId > <version > 1.18.28</version > <scope > provided</scope > </dependency >
在实体类上使用即可
@Data @NoArgsConstructor @AllArgsConstructor , @Getter @Setter @ToString @RequiredArgsConstructor
多对一处理
1.导入lombok导包
2.新建实体类Teacher,.Student
@Data public class Teacher { private int id; private String name; } @Data public class Student { private int id; private String name; private Teacher teacher; }
3.建立Mapper接口
public interface StudentMapper {} public interface TeacherMapper { @Select("select * from teacher where id = #{tid}") Teacher getTeacher (@Param("id") int id) ; }
4.建立Mapper,XML文件
5.在核心配置文件中绑定注册我们的Mapper接口或者文件!【class】
<mappers > <mapper class ="com.chen.dao.TeacherMapper" /> <mapper class ="com.chen.dao.StudentMapper" /> </mappers >
6.测试查询是否能够成功!
按照查询嵌套处理–子查询 <select id ="getStudent" resultMap ="StudentTeacher" > select * from student </select > <resultMap id ="StudentTeacher" type ="Student" > <result property ="id" column ="id" /> <result property ="name" column ="name" /> <association property ="teacher" column ="tid" javaType ="Teacher" select ="getTeacher" /> </resultMap > <select id ="getTeacher" resultType ="Teacher" > select * from teacher where id = #{id} </select >
按照结果嵌套查询 <select id ="getStudent2" resultMap ="StudentTeacher2" > select s.id sid,s.name sname,t.id tid,t.name tname from student s,teacher t where s.tid = t.id </select > <resultMap id ="StudentTeacher2" type ="Student" > <result property ="id" column ="sid" /> <result property ="name" column ="sname" /> <association property ="teacher" javaType ="Teacher" > <result property ="name" column ="tname" /> </association > </resultMap >
一对多处理
实体类
@Data public class Student { private int id; private String name; private int tid; }
@Data public class Teacher { private int id; private String name; private List<Student> students; }
按照查询嵌套处理–子查询 <select id ="getTeacher2" resultMap ="TeacherStudent2" > select * from mybatisb.teacher where id =#{tid} </select > <resultMap id ="TeacherStudent2" type ="Teacher" > <collection property ="students" javaType ="ArrayList" ofType ="Student" select ="getStudentByTeacherID" column ="id" /> </resultMap > <select id ="getStudentByTeacherID" resultType ="Student" > select id,name,tid from student where tid = #{tid} </select >
按照结果嵌套查询 <select id ="getTeacher" resultMap ="TeacherStudent" > select s.id sid,s.name sname,t.name tname,t.id tid from student s,teacher t where t.id=s.tid and t.id=#{tid} </select > <resultMap id ="TeacherStudent" type ="Teacher" > <result property ="id" column ="tid" /> <result property ="name" column ="tname" /> <collection property ="students" ofType ="Student" > <result property ="id" column ="sid" /> <result property ="name" column ="sname" /> <result property ="tid" column ="tid" /> </collection > </resultMap >
1.关联-association【多对一】 2.集合- collection【一对多】 3.javaType & of Type 1.JavaType :用来指定实体类中指定的类型 :(Teacher / ArrayList) 2.ofType :用来指定映射到List或者集合中的pojo类型 ,泛型中的约束类型!
面试高频
Mysql引擎
InnoDB底层原理
索引
索引优化!
联表查询总结 <resultMap id =" SQL标签的resultMap " type =" 类型 " > <result property ="映射的属性" column ="数据库字段" /> <association property ="映射的对象属性名" column ="传递查询的主键" javaType ="映射的对象类型" select ="嵌套的SQL的id" /> <collection property ="映射的对象属性名" javaType ="ArrayList(本质上是一个集合)" ofType ="泛型" select ="嵌套的SQL的id" column ="传递查询的主键" /> <collection property ="students" ofType ="Student" > </collection > </resultMap >
association :对象【多对一】
collection :集合【一对多】
ofType :用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!(如 List students –> List的类型为Stduent。则泛型为Student)
动态SQL
@SuppressWarnings("all") public class IDutils { public static String getId () { return UUID.randomUUID().toString().replaceAll("-" ,"" ); } @Test public void test () { System.out.println(IDutils.getId()); } }
1.导包
2.编写配置文件
<settings > <setting name ="logImpl" value ="STDOUT_LOGGING" /> <setting name ="mapUnderscoreToCamelCase" value ="true" /> </settings >
3.编写实休类
@Data public class Blog { private String id; private String title; private String author; private Date createTime; private int views; }
4.靠写实体类对应Mapper接口和Mapper.XML文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace ="com.chen.dao.BlogMapper" > <insert id ="addBlog" parameterType ="blog" > insert into mybatisb.blog (id,title,author,create_time,views) values (#{id},#{title},#{author},#{createTime},#{views}); </insert > </mapper >
5.test
Blog blog = new Blog ();blog.setId(IDutils.getId()); blog.setTitle("Mybatis.如此简单" ); blog.setAuthor("CCCHEN" ); blog.setCreateTime(new Date ()); blog.setViews(9999 ); mapper.addBlog(blog);
IF
传递 1 or 多值,根据这个字段找对应的记录,如果不传值则查询全部
追加
List<Blog> queryBlogIf (Map map) ; <select id="queryBlogIf" parameterType="map" resultType="blog" > select * from mybatisb.blog where 1 =1 <if test="title!= null" > and title = #{title} </if > <if test="author != null" > and author = #{author} </if > </select> HashMap map = new HashMap ();map.put("title" ,"Mybatis如此简单" ); List<Blog> blogs =mapper.queryBlogIf(map);
trim(where,set) where
where 元素只会在至少有一个子元素的条件返回SQL子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where元素也会将它们去除。
使用拼接语句,在sql上不用添加where 1=1 :使用< where >
当返回只有一个语句的时候,如果前面带 and / or ,会自动去除,
多个则判断第一个语句返回有没有 and / or ,有则去除,
使拼接后为 where 条件 and / or 条件
如果条件为空,where 自动去除
<select id ="queryBlogIf" parameterType ="map" resultType ="blog" > select * from mybatisb.blog <where > <if test ="title!= null" > title = #{title} </if > <if test ="author!= null" > and author = #{author} </if > </where > </select >
set(更新) set元素会动态前置SET关键字,同时也会删掉无关的逗号
<update id ="updateBlog" parameterType ="map" > update mybatisb.blog <set > <if test ="title!=null" > title=#{title}, </if > <if test ="author!=null" > author=#{author} </if > </set > where id =#{id} </update >
Choose(when,otherwise) 选择:止步于当前满足的语句
<select id ="queryBlogChoose" parameterType ="map" resultType ="blog" > select * from mybatisb.blog <where > <choose > <when test ="title!=null" > title = #{title} </when > <when test ="author!=null" > and author=#{author} </when > <otherwise > and views=#{views} </otherwise > </choose > </where > </select >
SQL片段
1、使用SQL 标签提提取,设置ID
<sql id ="if-title-author" > <if test ="title!= null" > title = #{title} </if > <if test ="author!= null" > and author = #{author} </if > </sql >
注意事项:
最好甚于单表来定义SQL片段!
不要存在where语句
2、使用include 标签引用
<select id ="queryBlogIf" parameterType ="map" resultType ="blog" > select * from mybatisb.blog <where > <include refid ="if-title-author" > </include > </where > </select >
Foreach select * from mybatisb.blog where 1 = 1 and (id= 1 or id= 2 or id= 3 )
以下拼接添加到sql语句中
collection :迭代的集合对象
item :遍历到的当前对象
open :开头
close :结尾
se parator:迭代对象(分隔符)
<!-- 原SQL:select * from mybatisb.blog where 1 =1 and (id=1 or id=2 or id=3 ) 使用map传递一个集合 item="id" :遍历出来的局部变量 --> <select id="queryBlogForeach" parameterType="map" resultType="Blog" > select * from mybatisb.blog <where> <foreach collection="ids" item="id" open=" and (" close=")" separator="or" > id=#{id} </foreach> </where> </select>
List<Blog> queryBlogForeach (Map map) ; HashMap map = new HashMap ();ArrayList<Integer> ids = new ArrayList <>(); ids.add(1 );ids.add(2 ); ids.add(3 );ids.add(4 ); map.put("ids" ,ids); List<Blog> blogs=mapper.queryBlogForeach(map);
总结 动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
现在Mysq中写出完整的SQL,再对应的去修改成为我们的动态SQL实现通用即可!
缓存 原理
一级缓存
小结:一级缓存默认是开启的,只在一次SglSession中有效,也就是学到连接到关闭连接这个区间段!
一级缓存就是一个Map。
清理一级缓存:sqlSession.clearCache()
缓存失效的情况:
1.查询不同的东西
2.增删改操作,可能会改变原来的数据,所以必定会刷新缓存!
3.查询不同的Mapper..xml
4.手动清理缓存!
二级缓存
1、开启全局缓存
<setting name ="cacheEnabled" value ="true" />
2、在要使用二级缓存的Mapper .xml开启
也可以自定义参数
<cache eviction ="FIFO" flushInterval ="60000" s1ze ="512" readon1y ="true" />
3、测试
自定义缓存 Ehcache Ehcache是一种广泛使用的开源]ava分布式缓存。主要面向通用缓存
依赖
<dependency > <groupId > org.mybatis.caches</groupId > <artifactId > mybatis-ehcache</artifactId > <version > 1.1.0</version > </dependency >
在mappere中指定使用我们的ehcache缓存实现!
<!--在当前Mapper.xml中使用二级缓存--> <cacheItype="org.mybatis.caches.ehcache.Ehcachecache"/>
项目总结 表上锁
在执行中防止变动
sql 后 加 for update 排它锁
<select id ="selectByUidForUpdate" resultMap ="BaseResultMap" > select <include refid ="Base_Column_List" > </include > from u_finance_account where uid = #{uid} for update </select >
事务
@Transactional(rollbackFor = Exception.class)
if (rows < 1 ){ throw new RuntimeException ("生成收益计划,更新产品状态为2失败" ); }