基础

  • 由ibatis改名
  • 是基于java的持久层框架,内部封装了JDBC
  • 使开发只关注SQL本身,无需关注驱动的加载、连接的维护、statement的创建等复杂过程
  • 过程
    • 主要通过XML或注解的方式配置将要执行的statement
    • 框架通过java对象和statement中的SQL动态参数映射生成最终要执行的SQL,并由Mybatis框架执行
    • 将结果直接映射为java对象
  • 采用了ORM思想解决了实体类与数据库表映射的问题

    入门

    数据库准备

    ``sql create tableteam(teamIdint NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '球队ID',teamNamevarchar(50) DEFAULT NULL COMMENT '球队名称',locationvarchar(50) DEFAULT NULL COMMENT '球队位置',createTime` date DEFAULT NULL COMMENT ‘球队建立时间’ ) ENGINE=InnoDB AUTO_INCREMENT=1003 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

INSERT INTO team VALUES (1001, ‘76人’, ‘宾夕法尼亚州费城’, ‘1967-01-01’); INSERT INTO team VALUES (1002, ‘篮网’, ‘纽约州布鲁克林’, ‘1967-01-01’); INSERT INTO team VALUES (1003, ‘雄鹿’, ‘威斯康星州密尔沃基’, ‘1968-01-01’); INSERT INTO team VALUES (1004, ‘黄蜂’, ‘夏洛特’, ‘2004-01-01’); INSERT INTO team VALUES (1005, ‘老鹰’, ‘乔治亚州亚特兰大市’, ‘1949-01-01’); INSERT INTO team VALUES (1006, ‘热火’, ‘佛罗里达州迈阿密’, ‘1988-01-01’); INSERT INTO team VALUES (1007, ‘凯尔特人’, ‘马赛诸萨州波士顿’, ‘1946-01-01’); INSERT INTO team VALUES (1008, ‘尼克斯’, ‘纽约州纽约市’, ‘1976-01-01’); INSERT INTO team VALUES (1009, ‘步行者’, ‘印第安纳波利斯’, ‘1967-01-01’); INSERT INTO team VALUES (1010, ‘公牛’, ‘伊利诺斯州芝加哥’, ‘1966-01-01’); INSERT INTO team VALUES (1011, ‘猛龙’, ‘加拿大安大略省多伦多’, ‘1995-01-01’); INSERT INTO team VALUES (1012, ‘骑士’, ‘俄亥俄州克里夫兰’, ‘1970-01-01’); INSERT INTO team VALUES (1013, ‘奇才’, ‘华盛顿D.C’, ‘1961-01-01’); INSERT INTO team VALUES (1014, ‘魔术’, ‘佛罗里达州奥兰多’, ‘1989-01-01’); INSERT INTO team VALUES (1015, ‘活塞’, ‘密歇根州底特律’, ‘1948-01-01’); INSERT INTO team VALUES (1016, ‘爵士’, ‘犹他州盐湖城’, ‘1974-01-01’); INSERT INTO team VALUES (1017, ‘太阳’, ‘亚利桑那州菲尼克斯’, ‘1968-01-01’); INSERT INTO team VALUES (1018, ‘快船’, ‘洛杉矶’, ‘1970-01-01’); INSERT INTO team VALUES (1019, ‘掘金’, ‘科罗拉多州丹佛’, ‘1976-01-01’); INSERT INTO team VALUES (1020, ‘湖人’, ‘加利福尼亚州洛杉矶’, ‘1948-01-01’); INSERT INTO team VALUES (1021, ‘开拓者’, ‘俄勒冈州波特兰’, ‘1970-01-01’); INSERT INTO team VALUES (1022, ‘独行侠’, ‘达拉斯’, ‘1980-01-01’); INSERT INTO team VALUES (1023, ‘灰熊’, ‘田纳西州孟菲斯’, ‘1995-01-01’); INSERT INTO team VALUES (1024, ‘马刺’, ‘德克萨斯州圣安东尼奥’, ‘1976-01-01’); INSERT INTO team VALUES (1025, ‘勇士’, ‘加州奥克兰’, ‘1946-01-01’); INSERT INTO team VALUES (1026, ‘鹈鹕’, ‘新奥尔良’, ‘1988-01-01’); INSERT INTO team VALUES (1027, ‘国王’, ‘加州萨科拉门托’, ‘1948-01-01’); INSERT INTO team VALUES (1028, ‘雷霆’, ‘俄克拉荷马州俄克拉荷马城’, ‘1967-01-01’); INSERT INTO team VALUES (1029, ‘火箭’, ‘德克萨斯州休斯顿’, ‘1967-01-01’); INSERT INTO team VALUES (1030, ‘森林狼’, ‘明尼苏达州明尼阿波利斯’, ‘1989-01-01’); INSERT INTO team VALUES (1047, ‘lina的球队’, ‘洛杉矶’, ‘2021-04-14’); INSERT INTO team VALUES (1053, ‘lina的球队’, ‘洛杉矶’, ‘2021-04-16’); INSERT INTO team VALUES (1054, ‘开课吧球队1’, ‘洛杉矶’, ‘2021-04-16’);

  1. <a name="smqaG"></a>
  2. ## maven项目pom.xml
  3. ```xml
  4. <?xml version="1.0" encoding="UTF-8"?>
  5. <project xmlns="http://maven.apache.org/POM/4.0.0"
  6. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  7. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  8. <modelVersion>4.0.0</modelVersion>
  9. <groupId>com.demo</groupId>
  10. <artifactId>mybatisdemo</artifactId>
  11. <version>1.0-SNAPSHOT</version>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.mybatis</groupId>
  15. <artifactId>mybatis</artifactId>
  16. <version>3.5.6</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>mysql</groupId>
  20. <artifactId>mysql-connector-java</artifactId>
  21. <version>8.0.23</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>junit</groupId>
  25. <artifactId>junit</artifactId>
  26. <version>4.12</version>
  27. <scope>test</scope>
  28. </dependency>
  29. <dependency>
  30. <groupId>log4j</groupId>
  31. <artifactId>log4j</artifactId>
  32. <version>1.2.17</version>
  33. </dependency>
  34. </dependencies>
  35. <build>
  36. <resources>
  37. <resource>
  38. <directory>src/main/java</directory>
  39. <includes>
  40. <include>**/*.xml</include>
  41. <include>**/*.properties</include>
  42. </includes>
  43. <filtering>false</filtering>
  44. </resource>
  45. </resources>
  46. <plugins>
  47. <plugin>
  48. <groupId>org.apache.maven.plugins</groupId>
  49. <artifactId>maven-compiler-plugin</artifactId>
  50. <version>3.8.1</version>
  51. <configuration>
  52. <source>1.8</source>
  53. <target>1.8</target>
  54. </configuration>
  55. </plugin>
  56. </plugins>
  57. </build>
  58. </project>

全局配置文件mybatis.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <settings>
  7. <setting name="logImpl" value="LOG4J"/>
  8. </settings>
  9. <environments default="development">
  10. <environment id="development">
  11. <transactionManager type="JDBC"/>
  12. <dataSource type="POOLED">
  13. <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
  14. <property name="url" value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT"/>
  15. <property name="username" value="root"/>
  16. <property name="password" value="root"/>
  17. </dataSource>
  18. </environment>
  19. </environments>
  20. <mappers>
  21. <mapper resource="com/demo/pojo/Team.xml"/>
  22. </mappers>
  23. </configuration>

log4j配置文件

  1. # 全局日志配置
  2. log4j.rootLogger=DEBUG,stdout
  3. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  5. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

pojo及mapper文件

  1. package com.demo.pojo;
  2. import java.util.Date;
  3. public class Team {
  4. public String teamName;
  5. public String location;
  6. public Date createTime;
  7. public Integer teamId;
  8. @Override
  9. public String toString() {
  10. return "Team{" +
  11. "teamName='" + teamName + '\'' +
  12. ", location='" + location + '\'' +
  13. ", createTime=" + createTime +
  14. ", teamId=" + teamId +
  15. '}';
  16. }
  17. public String getTeamName() {
  18. return teamName;
  19. }
  20. public void setTeamName(String teamName) {
  21. this.teamName = teamName;
  22. }
  23. public String getLocation() {
  24. return location;
  25. }
  26. public void setLocation(String location) {
  27. this.location = location;
  28. }
  29. public Date getCreateTime() {
  30. return createTime;
  31. }
  32. public void setCreateTime(Date createTime) {
  33. this.createTime = createTime;
  34. }
  35. public Integer getTeamId() {
  36. return teamId;
  37. }
  38. public void setTeamId(Integer teamId) {
  39. this.teamId = teamId;
  40. }
  41. }
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.demo.pojo.Team">
  6. <select id="queryAll" resultType="com.demo.pojo.Team">
  7. select * from team;
  8. </select>
  9. <select id="queryById" resultType="com.demo.pojo.Team">
  10. select * from team where teamId=#{id};
  11. </select>
  12. <insert id="add" parameterType="com.demo.pojo.Team">
  13. insert into team (teamName,location,createTime) values ( #{teamName} , #{location}, #{createTime} );
  14. </insert>
  15. <update id="update" parameterType="com.demo.pojo.Team" >
  16. update team set teamName=#{teamName} where teamId=#{teamId};
  17. </update>
  18. <delete id="del" parameterType="com.demo.pojo.Team" >
  19. delete from team where teamId=#{teamId};
  20. </delete>
  21. </mapper>

测试文件

  1. package com.demo.test;
  2. import com.demo.pojo.Team;
  3. import org.apache.ibatis.io.Resources;
  4. import org.apache.ibatis.session.SqlSession;
  5. import org.apache.ibatis.session.SqlSessionFactory;
  6. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  7. import org.junit.After;
  8. import org.junit.Before;
  9. import org.junit.Test;
  10. import java.io.IOException;
  11. import java.io.Reader;
  12. import java.util.Date;
  13. import java.util.List;
  14. public class TestTeam {
  15. private String resource = "mybatis.xml";
  16. private SqlSession sqlSession = null;
  17. @Before
  18. public void before(){
  19. Reader reader = null;
  20. try {
  21. reader = Resources.getResourceAsReader(resource);
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  26. sqlSession = sqlSessionFactory.openSession();
  27. }
  28. @After
  29. public void after(){
  30. sqlSession.close();
  31. }
  32. @Test
  33. public void testSelectList(){
  34. List<Team> list = sqlSession.selectList("com.demo.pojo.Team.queryAll");
  35. for(Team team : list){
  36. System.out.println(team);
  37. }
  38. }
  39. @Test
  40. public void testSelectOne(){
  41. Team team = sqlSession.selectOne("com.demo.pojo.Team.queryById",1001);
  42. System.out.println(team);
  43. }
  44. @Test
  45. public void testInsert(){
  46. Team team = new Team();
  47. team.setTeamName("测试名称");
  48. team.setLocation("测试地址");
  49. team.setCreateTime(new Date());
  50. int num = sqlSession.insert("com.demo.pojo.Team.add", team);
  51. // 由于采用的事务管理器TM是JDBC,默认都会关闭自动提交
  52. // sqlSession对象在创建时可以指定是否启用自动提交 sqlSessionFactory.openSession(true|false);
  53. sqlSession.commit();
  54. System.out.println(num);
  55. }
  56. @Test
  57. public void testUpdate(){
  58. Team team = new Team();
  59. team.setTeamName("测试名称update");
  60. team.setTeamId(1052);
  61. int num = sqlSession.update("com.demo.pojo.Team.update", team);
  62. sqlSession.commit();
  63. System.out.println(num);
  64. }
  65. @Test
  66. public void testDelete(){
  67. Team team = new Team();
  68. team.setTeamName("测试名称update");
  69. team.setTeamId(1052);
  70. int num = sqlSession.delete("com.demo.pojo.Team.del", team);
  71. sqlSession.commit();
  72. System.out.println(num);
  73. }
  74. }

高级

ThreadLocal

  • 为每一个使用该变量的线程都提供一个变量值的副本
  • 每个线程都可以独立改变自己的副本而不和其他线程冲突
  • 即同一个变量在不同线程可以有不同的、互相不干扰的值 ```java package com.demo.test;

import java.util.ArrayList; import java.util.List;

public class TestThreadLocal { private ThreadLocal threadLocal = new ThreadLocal<>(); private List list= new ArrayList();

  1. class MyThread1 extends Thread{
  2. @Override
  3. public void run() {
  4. threadLocal.set("thread_local_1");
  5. list.add("list_1");
  6. System.out.println("MyThread1-----threadLocal-----"+threadLocal.get());
  7. System.out.println("MyThread1-----list------"+list.size());
  8. }
  9. }
  10. class MyThread2 extends Thread{
  11. @Override
  12. public void run() {
  13. threadLocal.set("thread_local_2");
  14. list.add("list_2");
  15. System.out.println("MyThread2-----threadLocal-----"+threadLocal.get());
  16. System.out.println("MyThread2-----list------"+list.size());
  17. }
  18. }
  19. public static void main(String[] args) {
  20. TestThreadLocal testThreadLocal = new TestThreadLocal();
  21. MyThread1 t1 = testThreadLocal.new MyThread1();
  22. MyThread2 t2 = testThreadLocal.new MyThread2();
  23. t1.start();
  24. t2.start();
  25. }

}

  1. ```java
  2. package com.demo.util;
  3. import org.apache.ibatis.io.Resources;
  4. import org.apache.ibatis.session.SqlSession;
  5. import org.apache.ibatis.session.SqlSessionFactory;
  6. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  7. import java.io.IOException;
  8. import java.io.Reader;
  9. public class MybatisUtil {
  10. private static ThreadLocal<SqlSession> threadLocalSqlSession = new ThreadLocal<>();
  11. private static SqlSessionFactory sqlSessionFactory;
  12. static {
  13. Reader reader = null;
  14. try {
  15. reader = Resources.getResourceAsReader("mybatis.xml");
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }
  19. sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  20. }
  21. public static SqlSession getSqlSession(){
  22. SqlSession sqlSession = threadLocalSqlSession.get();
  23. if(sqlSession == null){
  24. sqlSession = sqlSessionFactory.openSession();
  25. threadLocalSqlSession.set(sqlSession);
  26. }
  27. return sqlSession;
  28. }
  29. public static void closeSqlSession(){
  30. SqlSession sqlSession = threadLocalSqlSession.get();
  31. if(sqlSession != null){
  32. sqlSession.close();
  33. threadLocalSqlSession.remove();
  34. }
  35. }
  36. }

使用Mapper动态代理

  • 原来项目的DAO层有接口+实现类,在实现类中调用sqlSession的方法最终指向配置文件的方法
  • 为了进一步简化实现类代码的编写,可以由MyBatis结合映射文件自动生成动态代理,实现接口
  • 由原来的DAO层升级为Mapper层 ```java package com.demo.mapper;

import com.demo.pojo.Team;

import java.util.List;

public interface TeamMapper { List queryAll(); Team queryById(Integer teamId); int add(Team team); int update(Team team); int del(Integer teamId); }

  1. ```xml
  2. <?xml version="1.0" encoding="UTF-8" ?>
  3. <!DOCTYPE mapper
  4. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  5. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  6. <!-- 接口的FQDN -->
  7. <mapper namespace="com.demo.mapper.TeamMapper">
  8. <select id="queryAll" resultType="com.demo.pojo.Team">
  9. select * from team;
  10. </select>
  11. <select id="queryById" resultType="com.demo.pojo.Team">
  12. select * from team where teamId=#{id};
  13. </select>
  14. <insert id="add" parameterType="com.demo.pojo.Team">
  15. insert into team (teamName,location,createTime) values ( #{teamName} , #{location}, #{createTime} );
  16. </insert>
  17. <update id="update" parameterType="com.demo.pojo.Team" >
  18. update team set teamName=#{teamName} where teamId=#{teamId};
  19. </update>
  20. <delete id="del" parameterType="com.demo.pojo.Team" >
  21. delete from team where teamId=#{teamId};
  22. </delete>
  23. </mapper>
  1. package com.demo.test;
  2. import com.demo.dao.TeamDao;
  3. import com.demo.dao.TeamDaoImpl;
  4. import com.demo.mapper.TeamMapper;
  5. import com.demo.pojo.Team;
  6. import com.demo.util.MybatisUtil;
  7. import org.junit.Test;
  8. import java.util.Date;
  9. import java.util.List;
  10. public class TestTeamMapper {
  11. private TeamMapper teamMapper = MybatisUtil.getSqlSession().getMapper(TeamMapper.class);
  12. @Test
  13. public void testSelectList(){
  14. List<Team> list = teamMapper.queryAll();
  15. for(Team team : list){
  16. System.out.println(team);
  17. }
  18. }
  19. @Test
  20. public void testSelectOne(){
  21. Team team = teamMapper.queryById(1001);
  22. System.out.println(team);
  23. }
  24. @Test
  25. public void testInsert(){
  26. Team team = new Team();
  27. team.setTeamName("测试名称");
  28. team.setLocation("测试地址");
  29. team.setCreateTime(new Date());
  30. int num = teamMapper.add(team);
  31. MybatisUtil.getSqlSession().commit();
  32. System.out.println(num);
  33. }
  34. @Test
  35. public void testUpdate(){
  36. Team team = new Team();
  37. team.setTeamName("测试名称update");
  38. team.setTeamId(1052);
  39. int num = teamMapper.update(team);
  40. MybatisUtil.getSqlSession().commit();
  41. System.out.println(num);
  42. }
  43. @Test
  44. public void testDelete(){
  45. int num = teamMapper.del(1052);
  46. MybatisUtil.getSqlSession().commit();
  47. System.out.println(num);
  48. }
  49. }

Mapper中对象字段的钩子

  • service中插入数据时,有些字段是数据库自增的,想在代码中在插入成功后获取自增的ID
  • mapper中通过sql的 UUID() 生成ID后插入数据库

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <!-- 接口的FQDN -->
    6. <mapper namespace="com.demo.mapper.TeamMapper">
    7. <insert id="add" parameterType="com.demo.pojo.Team">
    8. <!-- keyProperty:标签内容的值赋值给哪个属性
    9. resultType:赋值属性的类型
    10. order:AFTER|BEFORE 表示标签内容的语句在外面的语句(前|后)执行
    11. -->
    12. <selectKey keyProperty="teamId" resultType="java.lang.Integer" order="AFTER" >
    13. select LAST_INSERT_ID();
    14. </selectKey>
    15. <!--
    16. <selectKey keyProperty="teamId" resultType="java.lang.String" order="BEFORE" >
    17. select UUID();
    18. </selectKey>
    19. -->
    20. insert into team (teamName,location,createTime) values ( #{teamName} , #{location}, #{createTime} );
    21. </insert>
    22. </mapper>

    输入参数映射

  • 在mybatis3.4版本之前可以使用 #{0}、#{1} … 传入多个参数

  • 在mybatis3.4版本之后可以使用 #{arg0}、#{arg1} … 或 #{param1}、#{param2}…传入多个参数
  • 也可以在对应接口的代码中通过 @Param(‘别名’) Type Var 后,通过 #{别名} 方式使用
  • 也可以传入map、pojo,使用时直接#{} 指定 map的键名即可 ```xml public interface TeamMapper { int queryByRange(@Param(“min”) Integer min , @Param(“max”) Integer max); }

  1. <a name="qIMFy"></a>
  2. ## ${}与#{}
  3. - #{} 在sql中提现的是?占位符,然后通过prepareStatement()进行变量替换设置
  4. - ${} 在sql中提现的是直接替换,直接拼接到sql中
  5. <a name="if19p"></a>
  6. ## resultMap
  7. - 可以自定义sql结果和java对象属性的映射关系,更灵活的指定映射关系
  8. - 一般用在两边不一致的情况
  9. ```xml
  10. <?xml version="1.0" encoding="UTF-8" ?>
  11. <!DOCTYPE mapper
  12. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  13. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  14. <!-- 接口的FQDN -->
  15. <mapper namespace="com.demo.mapper.TeamMapper">
  16. <!-- resultMap 和 resultType 不能同时存在 -->
  17. <select id="queryByRange" resultMap="myResultMap">
  18. select * from team when teamId>=#{min} and teamId&lt;=#{max};
  19. </select>
  20. <!-- resultMap 自定义映射关系,type指定期望的类型 -->
  21. <resultMap id="myResultMap" type="com.demo.pojo.Team">
  22. <!-- 一般主键用id 表示 ,其他键用result
  23. column 表示数据库表的列名,
  24. jdbcType 表示数据库表的列名类型,一般可以省略
  25. property 表示实体类属性名,
  26. javaType 表示实体类属性类型,一般可以省略
  27. -->
  28. <id column="teamId" property="teamId" javaType="java.lang.Integer"></id>
  29. <result column="teamName" property="teamName" javaType="java.lang.String"></result>
  30. </resultMap>
  31. <!-- 根据已有的ResultMap 扩展 -->
  32. <resultMap id="extendMyResultMap" type="com.demo.pojo.Team" extends="myResultMap">
  33. <result column="teamName1" property="teamName1" javaType="java.lang.String"></result>
  34. </resultMap>
  35. <!-- 根据已有的ResultMap 扩展后并引用外部RM -->
  36. <resultMap id="extendMyResultMap" type="com.demo.pojo.Team" extends="myResultMap">
  37. <association property="需要赋值的字段" resultMap="需要引用的外部RM的文件.id" />
  38. </resultMap>
  39. <!-- 根据已有的ResultMap 扩展后并再次通过一条sql语句执行结果后进行映射 -->
  40. <resultMap id="extendMyResultMap" type="com.demo.pojo.Team" extends="myResultMap">
  41. <!-- association 对一的关系 -->
  42. <association property="需要赋值的字段" select="com.demo.mapper.TeamMapper.queryById" column="teamId"/>
  43. <!-- collection 对多的关系 javaType多的类型一般是集合,ofType就是集合内元素的类型 -->
  44. <collection property="需要赋值的字段" javaType="arrayList" ofType="Player" ( resultMap= | select= )/>
  45. </resultMap>
  46. </mapper>

全局配置文件

  1. # jdbc.properties
  2. jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
  3. jdbc.driver=com.mysql.cj.jdbc.Driver
  4. jdbc.username=root
  5. jdbc.password=root
  1. <configuration>
  2. <properties resource="jdbc.properties" />
  3. <settings>
  4. <setting name="logImpl" value="LOG4J"/>
  5. </settings>
  6. <typeAliases>
  7. <typeAliase type="FQDN" alias="aliasName"></typeAliase>
  8. <!-- 扫描全包,扫描后各mapper文件的type的FQDN可以简写为文件名,并且首字母不区分大小写 -->
  9. <package name=""></package>
  10. </typeAliases>
  11. <environments default="development">
  12. <environment id="development">
  13. <transactionManager type="JDBC"/>
  14. <dataSource type="POOLED">
  15. <property name="driver" value="${jdbc.driver}"/>
  16. <property name="url" value="${jdbc.url}"/>
  17. <property name="username" value="${jdbc.username}"/>
  18. <property name="password" value="${jdbc.password}"/>
  19. </dataSource>
  20. </environment>
  21. </environments>
  22. <!--
  23. <mappers>
  24. <mapper resource="com/demo/pojo/Team.xml"/>
  25. </mappers>
  26. 指定包下所有的mapper接口,要求Mapper接口名称和映射文件同包同名
  27. -->
  28. <package name="com.demo.mapper" ></package>
  29. </configuration>

动态SQL

  1. <!-- 动态查询 -->
  2. <select id="queryByVO" parameterType="QueryVO" >
  3. select * from team
  4. <where>
  5. <!-- 根据if条件动态拼接sql,条件里的and关键字框架会自动添加或删除 -->
  6. <if test="name != null" >
  7. and teamName like concat(concat('%',#{name}),'%')
  8. </if>
  9. <if test="location != null" >
  10. and location=#{location};
  11. </if>
  12. </where>
  13. </select>
  14. <!-- 动态更新 -->
  15. <update id="update1" parameterType="Team" >
  16. update team
  17. <set>
  18. <!-- 根据if条件动态拼接sql -->
  19. <if test="teamName != null" >
  20. teamName=#{teamName},
  21. </if>
  22. <if test="location != null" >
  23. location=#{location},
  24. </if>
  25. </set>
  26. where teamId=#{teamId}
  27. </update>
  28. <!-- 批量插入 -->
  29. <insert id="addList" parameterType="arraylist">
  30. insert into team(teamName,location) values
  31. <foreach collection="list" item="t" separator="," >
  32. (#{t.teamName},#{t.location})
  33. </foreach>
  34. </insert>
  35. <!-- 批量删除 -->
  36. <delete id="delList" >
  37. delete from team where teamId in
  38. <foreach collection="list" item="t" separator="," open="(" close=")" >
  39. #{t}
  40. </foreach>
  41. </delete>

缓存

Mybatis一级缓存

  • 自动开启,sqlSession级别
  • sqlSession断开连接了一级缓存也会被清空
  • 增、删、改了相应表的数据并commit/rollback后缓存也会被清空
  • 可以调用session.clearCache() 清空本地缓存

    Mybatis二级缓存

  • 手动开启,多sqlSession共享,同一个namespace的mapper级别的缓存

  • 增、删、改了相应表的数据并commit/rollback后缓存也会被清空
  • 如果两个session不是从同一个Factory获取,二级缓存也不会生效
  • 单个select语句可以通过useCache=false禁用二级缓存
  • 开启步骤

    1. mybatis.xml全局开启

      1. <settings>
      2. <setting name="cacheEnabled" value="true"></setting>
      3. </settings>
    2. mapper文件中开启

      1. <mapper namespace="">
      2. <cache>
      3. <property name="eviction" value="LRU" />
      4. <!-- 超过size后采用上面的驱逐策略进行删除 -->
      5. <property name="size" value="1024" />
      6. <property name="flushInterval" value="60000" />
      7. <property name="readOnly" value="true" />
      8. </cache>
      9. <!-- 也可以引用其他已经写好的cache配置 -->
      10. <cache-ref namespace="" />
      11. </mapper>
    3. 实体类实现Serializable接口

      分页插件

  • 配置依赖

    1. <dependency>
    2. <groupId>com.github.pagehelper</groupId>
    3. <artifactId>pagehelper</artifactId>
    4. <version>5.1.10</version>
    5. </dependency>
  • 配置插件

    1. <!-- mybatis全局配置文件 -->
    2. <plugins>
    3. <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    4. </plugins>
  • 使用插件 ```java @Test public void test(){ // 此方法设置分页,参数为页码,条数,此方法必须在查询方法上面一行 // 查询方法都是复用不加limit的查询方法,插件会自动拼接limit PageHelper.startPage(2,10); List teams = teamMapper.queryAll(); teams.forEach(team->System.out.println(team));

    PageInfo info = new PageInfo<>(teams); System.out.println(“当前页:” + info.getPageNum()); System.out.println(“总页数:” + info.getPages()); System.out.println(“前一页:” + info.getPrevPage()); System.out.println(“后一页:” + info.getNextPage()); for(int num: info.getNavigatepageNums()){

    1. System.out.println(num);

    }

}

  1. <a name="WJTca"></a>
  2. ## 反向生成插件
  3. - 配置依赖
  4. ```xml
  5. <build>
  6. <plugins>
  7. <plugin>
  8. <groupId>org.mybatis.generator</groupId>
  9. <artifactId>mybatis-generator-maven-plugin</artifactId>
  10. <version>1.3.5</version>
  11. <configuration>
  12. <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
  13. <overwrite>true</overwrite>
  14. </configuration>
  15. <dependencies>
  16. <dependency>
  17. <groupId>org.mybatis.generator</groupId>
  18. <artifactId>mybatis-generator-core</artifactId>
  19. <version>1.3.5</version>
  20. </dependency>
  21. </dependencies>
  22. </plugin>
  23. </plugins>
  24. </build>
  • 配置文件generatorConfig.xml ```xml <?xml version=”1.0” encoding=”UTF-8”?> <!DOCTYPE generatorConfiguration
    1. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
    2. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

  1. <context id="MyBatis" targetRuntime="MyBatis3">
  2. <!--去除注释 -->
  3. <commentGenerator>
  4. <property name="suppressAllComments" value="true" />
  5. </commentGenerator>
  6. <!--2、数据库连接 -->
  7. <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
  8. connectionURL="jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT"
  9. userId="root"
  10. password="root">
  11. </jdbcConnection>
  12. <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer;
  13. 为 true时把JDBC DECIMAL和NUMERIC类型解析为java.math.BigDecimal -->
  14. <javaTypeResolver>
  15. <property name="forceBigDecimals" value="false" />
  16. </javaTypeResolver>
  17. <!--3、生成实体类 指定包名 以及生成的地址 (可以自定义地址,但是路径不存在不会自动创建
  18. 使用Maven生成在target目录下,会自动创建) -->
  19. <javaModelGenerator targetPackage="com.demo.pojo"
  20. targetProject="src\main\java">
  21. <property name="trimStrings" value="true" />
  22. </javaModelGenerator>
  23. <!--4、生成SQLmapper.xml映射文件 -->
  24. <sqlMapGenerator targetPackage="com.demo.mapper"
  25. targetProject="src\main\resources">
  26. </sqlMapGenerator>
  27. <!--5、生成Dao(Mapper)接口文件,-->
  28. <javaClientGenerator type="XMLMAPPER"
  29. targetPackage="com.demo.mapper"
  30. targetProject="src\main\java">
  31. </javaClientGenerator>
  32. <!--6、要生成哪些表(更改tableName和domainObjectName就可以) -->
  33. <!-- tableName:要生成的表名
  34. enableCountByExample:Count语句中加入where条件查询,默认为true开启
  35. enableUpdateByExample:Update语句中加入where条件查询,默认为true开启
  36. enableDeleteByExample:Delete语句中加入where条件查询,默认为true开启
  37. enableSelectByExample:Select多条语句中加入where条件查询,默认为true开启
  38. selectByExampleQueryId:Select单个对象语句中加入where条件查询,默认为true开启
  39. -->
  40. <table tableName="Team"
  41. enableCountByExample="false"
  42. enableUpdateByExample="false"
  43. enableUpdateByPrimaryKey="false"
  44. enableDeleteByExample="false"
  45. enableDeleteByPrimaryKey="false"
  46. enableSelectByExample="false"
  47. selectByExampleQueryId="false">
  48. <property name="useActualColumnNames" value="true"/>
  49. </table>
  50. </context>

  1. - 使用插件
  2. - 双击mvn插件 mybatis.generator
  3. - build success即可看到
  4. - 测试
  5. ```java
  6. package com.demo.test;
  7. import com.demo.util.MybatisUtil;
  8. import org.junit.Test;
  9. import org.demo.mapper.TeamMapper;
  10. import org.demo.pojo.Team;
  11. import org.demo.pojo.TeamExample;
  12. import java.util.List;
  13. /**
  14. * ClassName: TestGenerator
  15. * 测试类
  16. */
  17. public class TestGenerator {
  18. private TeamMapper mapper= MybatisUtil.getSqlSession().getMapper(TeamMapper.class);
  19. @Test
  20. public void test1(){
  21. Team team = mapper.selectByPrimaryKey(1001);
  22. System.out.println(team);
  23. }
  24. @Test
  25. public void test2(){
  26. //为多条件排序查询服务
  27. TeamExample example=new TeamExample();
  28. //看做条件的容器
  29. TeamExample.Criteria criteria = example.createCriteria();
  30. //往容器中添加条件
  31. criteria.andTeamNameLike("%人%");
  32. criteria.andTeamIdBetween(1001,1020);
  33. List<Team> teams = mapper.selectByExample(example);
  34. for (Team team : teams) {
  35. System.out.println(team);
  36. }
  37. }
  38. }