第一章:前言

  • 注解开发虽然不如 XML 开发那样,可以完全做到代码和配置文件分离,但是其开发灵活快速的特性,使得在企业开发中的地位日益显著,而 Mybatis 作为时下最流行的持久层框架,掌握 Mybatis 注解开发势在必行。

第二章:环境准备

  • sql 脚本:
  1. -- ----------------------------
  2. -- Table structure for account
  3. -- ----------------------------
  4. DROP TABLE IF EXISTS `account`;
  5. CREATE TABLE `account` (
  6. `id` int(11) NOT NULL AUTO_INCREMENT,
  7. `user_id` int(11) NULL DEFAULT NULL COMMENT '外键',
  8. `money` double NULL DEFAULT NULL COMMENT '存款',
  9. PRIMARY KEY (`id`) USING BTREE,
  10. INDEX `fk_user_id`(`user_id`) USING BTREE,
  11. CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
  12. ) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
  13. -- ----------------------------
  14. -- Records of account
  15. -- ----------------------------
  16. INSERT INTO `account` VALUES (1, 1, 5000);
  17. INSERT INTO `account` VALUES (2, 2, 2000);
  18. INSERT INTO `account` VALUES (3, 3, 3000);
  19. -- ----------------------------
  20. -- Table structure for course
  21. -- ----------------------------
  22. DROP TABLE IF EXISTS `course`;
  23. CREATE TABLE `course` (
  24. `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  25. `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '课程名称',
  26. PRIMARY KEY (`id`) USING BTREE
  27. ) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
  28. -- ----------------------------
  29. -- Records of course
  30. -- ----------------------------
  31. INSERT INTO `course` VALUES (1, '语文');
  32. INSERT INTO `course` VALUES (2, '数学');
  33. INSERT INTO `course` VALUES (3, '英语');
  34. -- ----------------------------
  35. -- Table structure for student
  36. -- ----------------------------
  37. DROP TABLE IF EXISTS `student`;
  38. CREATE TABLE `student` (
  39. `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  40. `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '学生姓名',
  41. `age` int(11) NULL DEFAULT NULL COMMENT '学生年龄',
  42. PRIMARY KEY (`id`) USING BTREE
  43. ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
  44. -- ----------------------------
  45. -- Records of student
  46. -- ----------------------------
  47. INSERT INTO `student` VALUES (1, '张三', 20);
  48. INSERT INTO `student` VALUES (2, '李四', 25);
  49. -- ----------------------------
  50. -- Table structure for student_course
  51. -- ----------------------------
  52. DROP TABLE IF EXISTS `student_course`;
  53. CREATE TABLE `student_course` (
  54. `sid` int(11) NULL DEFAULT NULL COMMENT '外键,指向学生表的主键',
  55. `cid` int(11) NULL DEFAULT NULL COMMENT '外键,指向课程表的主键',
  56. INDEX `fk_sid`(`sid`) USING BTREE,
  57. INDEX `fk_cid`(`cid`) USING BTREE,
  58. CONSTRAINT `fk_cid` FOREIGN KEY (`cid`) REFERENCES `course` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  59. CONSTRAINT `fk_sid` FOREIGN KEY (`sid`) REFERENCES `student` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
  60. ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
  61. -- ----------------------------
  62. -- Records of student_course
  63. -- ----------------------------
  64. INSERT INTO `student_course` VALUES (1, 1);
  65. INSERT INTO `student_course` VALUES (1, 2);
  66. INSERT INTO `student_course` VALUES (1, 3);
  67. INSERT INTO `student_course` VALUES (2, 3);
  68. -- ----------------------------
  69. -- Table structure for user
  70. -- ----------------------------
  71. DROP TABLE IF EXISTS `user`;
  72. CREATE TABLE `user` (
  73. `id` int(11) NOT NULL AUTO_INCREMENT,
  74. `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户名',
  75. `birthday` datetime(0) NULL DEFAULT NULL COMMENT '生日',
  76. `gender` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '性别',
  77. `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '地址',
  78. PRIMARY KEY (`id`) USING BTREE
  79. ) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
  80. -- ----------------------------
  81. -- Records of user
  82. -- ----------------------------
  83. INSERT INTO `user` VALUES (1, '张三', '2021-11-02 10:43:06', '男', '江苏苏州');
  84. INSERT INTO `user` VALUES (2, '李四', '2021-10-26 10:43:24', '女', '江苏南京');
  85. INSERT INTO `user` VALUES (3, '王五', '2021-10-26 10:43:45', '男', '江苏徐州');
  • 导入相关 jar 包的 Maven 坐标:
  1. <dependency>
  2. <groupId>org.mybatis</groupId>
  3. <artifactId>mybatis</artifactId>
  4. <version>3.4.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>log4j</groupId>
  8. <artifactId>log4j</artifactId>
  9. <version>1.2.17</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>mysql</groupId>
  13. <artifactId>mysql-connector-java</artifactId>
  14. <version>8.0.21</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>junit</groupId>
  18. <artifactId>junit</artifactId>
  19. <version>4.13</version>
  20. <scope>test</scope>
  21. </dependency>
  • mybatis-config.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. <environments default="development">
  7. <environment id="development">
  8. <transactionManager type="JDBC"/>
  9. <dataSource type="POOLED">
  10. <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
  11. <property name="url"
  12. value="jdbc:mysql://192.168.134.100:3306/test?useUnicode=true&amp;characterEncoding=UTF-8&amp;autoReconnect=true&amp;useSSL=false&amp;serverTimezone=GMT%2B8&amp;allowPublicKeyRetrieval=true"/>
  13. <property name="username" value="root"/>
  14. <property name="password" value="123456"/>
  15. </dataSource>
  16. </environment>
  17. </environments>
  18. <mappers>
  19. <package name="com.github.mapper"/>
  20. </mappers>
  21. </configuration>
  • log4j.xml
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
  3. <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  4. <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
  5. <param name="Encoding" value="UTF-8" />
  6. <layout class="org.apache.log4j.PatternLayout">
  7. <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
  8. </layout>
  9. </appender>
  10. <logger name="java.sql">
  11. <level value="debug" />
  12. </logger>
  13. <logger name="org.apache.ibatis">
  14. <level value="info" />
  15. </logger>
  16. <root>
  17. <level value="debug" />
  18. <appender-ref ref="STDOUT" />
  19. </root>
  20. </log4j:configuration>

第三章:Mybatis 注解实现常用的 CRUD

  • User.java
  1. package com.sunxiaping.domain;
  2. import java.io.Serializable;
  3. import java.util.Date;
  4. public class User implements Serializable {
  5. private Integer id;
  6. private String username;
  7. private Date birthday;
  8. private String gender;
  9. private String address;
  10. public Integer getId() {
  11. return id;
  12. }
  13. public void setId(Integer id) {
  14. this.id = id;
  15. }
  16. public String getUsername() {
  17. return username;
  18. }
  19. public void setUsername(String username) {
  20. this.username = username;
  21. }
  22. public Date getBirthday() {
  23. return birthday;
  24. }
  25. public void setBirthday(Date birthday) {
  26. this.birthday = birthday;
  27. }
  28. public String getGender() {
  29. return gender;
  30. }
  31. public void setGender(String gender) {
  32. this.gender = gender;
  33. }
  34. public String getAddress() {
  35. return address;
  36. }
  37. public void setAddress(String address) {
  38. this.address = address;
  39. }
  40. @Override
  41. public String toString() {
  42. return "User{" +
  43. "id=" + id +
  44. ", username='" + username + '\'' +
  45. ", birthday=" + birthday +
  46. ", gender='" + gender + '\'' +
  47. ", address='" + address + '\'' +
  48. '}';
  49. }
  50. }
  • UserMapper.java
  1. package com.sunxiaping.mapper;
  2. import com.sunxiaping.domain.User;
  3. import org.apache.ibatis.annotations.*;
  4. import java.util.List;
  5. public interface UserMapper {
  6. /**
  7. * 查询所有用户信息
  8. *
  9. * @return
  10. */
  11. @Select(" SELECT * FROM `user`")
  12. @Results({
  13. @Result(id = true, property = "id", column = "id"),
  14. @Result(property = "username", column = "username"),
  15. @Result(property = "birthday", column = "birthday"),
  16. @Result(property = "gender", column = "gender"),
  17. @Result(property = "address", column = "address"),
  18. })
  19. List<User> findAll();
  20. /**
  21. * 添加用户信息
  22. *
  23. * @param user
  24. */
  25. @Insert(" INSERT INTO `user` (username,birthday,gender,address) VALUES (#{username},#{birthday},#{gender},#{address})")
  26. void saveUser(User user);
  27. /**
  28. * 修改用户信息
  29. *
  30. * @param user
  31. */
  32. @Update(" UPDATE `user` set username = #{username},gender= #{gender} ,address = #{address} WHERE id = #{id} ")
  33. void updateUser(User user);
  34. /**
  35. * 删除用户信息
  36. *
  37. * @param id
  38. */
  39. @Delete(" DELETE FROM `user` WHERE id = #{id} ")
  40. void deleteById(Integer id);
  41. }
  • 测试:
  1. package com.sunxiaping;
  2. import com.sunxiaping.domain.User;
  3. import com.sunxiaping.mapper.UserMapper;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. import org.junit.After;
  9. import org.junit.Before;
  10. import org.junit.Test;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.util.Date;
  14. import java.util.List;
  15. public class UserTest {
  16. SqlSessionFactory sqlSessionFactory = null;
  17. SqlSession sqlSession = null;
  18. @Before
  19. public void before() throws IOException {
  20. String resource = "mybatis-config.xml";
  21. InputStream inputStream = Resources.getResourceAsStream(resource);
  22. sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  23. }
  24. @After
  25. public void after() {
  26. if (sqlSession != null) {
  27. sqlSession.close();
  28. }
  29. }
  30. @Test
  31. public void testFindAll() throws IOException {
  32. sqlSession = sqlSessionFactory.openSession(true);
  33. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  34. List<User> userList = userMapper.findAll();
  35. System.out.println("userList = " + userList);
  36. }
  37. @Test
  38. public void testSaveUser() {
  39. sqlSession = sqlSessionFactory.openSession(true);
  40. User user = new User();
  41. user.setUsername("zhangsan");
  42. user.setBirthday(new Date());
  43. user.setGender("男");
  44. user.setAddress("江苏苏州");
  45. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  46. userMapper.saveUser(user);
  47. }
  48. @Test
  49. public void testUpdateUser() {
  50. sqlSession = sqlSessionFactory.openSession(true);
  51. User user = new User();
  52. user.setId(1);
  53. user.setUsername("张三");
  54. user.setGender("女");
  55. user.setAddress("江苏苏州");
  56. user.setBirthday(new Date());
  57. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  58. userMapper.updateUser(user);
  59. }
  60. @Test
  61. public void testDeleteById() {
  62. sqlSession = sqlSessionFactory.openSession(true);
  63. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  64. userMapper.deleteById(1);
  65. }
  66. }

第四章:Mybatis 注解实现一对一关联查询

  • 一对一的模型:

一对一的模型.png

  • 查询账号的同时查询用户的信息对应的 SQL :
  1. SELECT * FROM `account`
  1. SELECT * FROM `user` WHERE id = #{id}
  • 示例:
  • User.java
  1. package com.github.entity;
  2. import java.io.Serializable;
  3. import java.util.Date;
  4. /**
  5. * @author 许大仙
  6. * @version 1.0
  7. * @since 2021-11-02 10:42
  8. */
  9. public class User implements Serializable {
  10. private Integer id;
  11. private String username;
  12. private Date birthday;
  13. private String gender;
  14. private String address;
  15. public Integer getId() {
  16. return id;
  17. }
  18. public void setId(Integer id) {
  19. this.id = id;
  20. }
  21. public String getUsername() {
  22. return username;
  23. }
  24. public void setUsername(String username) {
  25. this.username = username;
  26. }
  27. public Date getBirthday() {
  28. return birthday;
  29. }
  30. public void setBirthday(Date birthday) {
  31. this.birthday = birthday;
  32. }
  33. public String getGender() {
  34. return gender;
  35. }
  36. public void setGender(String gender) {
  37. this.gender = gender;
  38. }
  39. public String getAddress() {
  40. return address;
  41. }
  42. public void setAddress(String address) {
  43. this.address = address;
  44. }
  45. @Override
  46. public String toString() {
  47. return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", gender='"
  48. + gender + '\'' + ", address='" + address + '\'' + '}';
  49. }
  50. }
  • Account.java
  1. package com.github.entity;
  2. import java.io.Serializable;
  3. /**
  4. * @author 许大仙
  5. * @version 1.0
  6. * @since 2021-11-02 10:44
  7. */
  8. public class Account implements Serializable {
  9. private Integer id;
  10. private Double money;
  11. /**
  12. * 一个账户属于一个用户
  13. */
  14. private User user;
  15. public Integer getId() {
  16. return id;
  17. }
  18. public void setId(Integer id) {
  19. this.id = id;
  20. }
  21. public Double getMoney() {
  22. return money;
  23. }
  24. public void setMoney(Double money) {
  25. this.money = money;
  26. }
  27. public User getUser() {
  28. return user;
  29. }
  30. public void setUser(User user) {
  31. this.user = user;
  32. }
  33. @Override
  34. public String toString() {
  35. return "Account{" + "id=" + id + ", money=" + money + ", user=" + user + '}';
  36. }
  37. }
  • UserMapper.java
  1. package com.github.mapper;
  2. import com.github.entity.User;
  3. import org.apache.ibatis.annotations.Mapper;
  4. import org.apache.ibatis.annotations.Result;
  5. import org.apache.ibatis.annotations.Results;
  6. import org.apache.ibatis.annotations.Select;
  7. /**
  8. * @author 许大仙
  9. * @version 1.0
  10. * @since 2021-11-02 10:45
  11. */
  12. @Mapper
  13. public interface UserMapper {
  14. @Select("SELECT * FROM `user` WHERE id = #{id}")
  15. @Results({
  16. @Result(id = true, property = "id", column = "id"),
  17. @Result(property = "username", column = "username"),
  18. @Result(property = "birthday", column = "birthday"),
  19. @Result(property = "gender", column = "gender"),
  20. @Result(property = "address", column = "address"),
  21. })
  22. User findById(Integer id);
  23. }
  • AccountMapper.java
  1. package com.github.mapper;
  2. import com.github.entity.Account;
  3. import com.github.entity.User;
  4. import org.apache.ibatis.annotations.*;
  5. import java.util.List;
  6. /**
  7. * @author 许大仙
  8. * @version 1.0
  9. * @since 2021-11-02 10:45
  10. */
  11. @Mapper
  12. public interface AccountMapper {
  13. @Select("SELECT * FROM `account`")
  14. @Results({
  15. @Result(id = true, property = "id", column = "id"),
  16. @Result(property = "money", column = "money"),
  17. @Result(
  18. property = "user",
  19. javaType = User.class,
  20. column = "user_id",
  21. one = @One(select = "com.github.mapper.UserMapper.findById")
  22. )
  23. })
  24. List<Account> findAll();
  25. }
  • 测试:
  1. package com.github.mybatis;
  2. import com.github.entity.Account;
  3. import com.github.mapper.AccountMapper;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. import org.junit.After;
  9. import org.junit.Before;
  10. import org.junit.Test;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.util.List;
  14. /**
  15. * @author 许大仙
  16. * @version 1.0
  17. * @since 2021-10-29 14:19
  18. */
  19. public class MybatisTest {
  20. SqlSession sqlSession;
  21. @Before
  22. public void before() throws IOException {
  23. // 使用Mybatis的Resources读取mybatis-config.xml配置文件
  24. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
  25. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  26. sqlSession = sqlSessionFactory.openSession();
  27. }
  28. @Test
  29. public void test() throws IOException {
  30. AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
  31. List<Account> accountList = accountMapper.findAll();
  32. accountList.forEach(System.out::println);
  33. }
  34. @After
  35. public void after() {
  36. if (null != sqlSession) {
  37. sqlSession.close();
  38. }
  39. }
  40. }

第五章:Mybatis 注解实现一对多关联查询

  • 一对多的模型:

一对多的模型.png

  • 查询用户的同时查询账号的信息对应的 SQL :
  1. SELECT * FROM `user`
  1. SELECT * FROM `account` where user_id = #{user_id}
  • 示例:
  • Account.java
  1. package com.github.entity;
  2. import java.io.Serializable;
  3. /**
  4. * @author 许大仙
  5. * @version 1.0
  6. * @since 2021-11-02 10:44
  7. */
  8. public class Account implements Serializable {
  9. private Integer id;
  10. private Double money;
  11. public Account(Integer id, Double money) {
  12. this.id = id;
  13. this.money = money;
  14. }
  15. public Integer getId() {
  16. return id;
  17. }
  18. public void setId(Integer id) {
  19. this.id = id;
  20. }
  21. public Double getMoney() {
  22. return money;
  23. }
  24. public void setMoney(Double money) {
  25. this.money = money;
  26. }
  27. @Override
  28. public String toString() {
  29. return "Account{" + "id=" + id + ", money=" + money + '}';
  30. }
  31. }
  • User.java
  1. package com.github.entity;
  2. import java.io.Serializable;
  3. import java.util.Date;
  4. import java.util.List;
  5. /**
  6. * @author 许大仙
  7. * @version 1.0
  8. * @since 2021-11-02 10:42
  9. */
  10. public class User implements Serializable {
  11. private Integer id;
  12. private String username;
  13. private Date birthday;
  14. private String gender;
  15. private String address;
  16. // 一个用户有多个账号
  17. private List<Account> accountList;
  18. public Integer getId() {
  19. return id;
  20. }
  21. public void setId(Integer id) {
  22. this.id = id;
  23. }
  24. public String getUsername() {
  25. return username;
  26. }
  27. public void setUsername(String username) {
  28. this.username = username;
  29. }
  30. public Date getBirthday() {
  31. return birthday;
  32. }
  33. public void setBirthday(Date birthday) {
  34. this.birthday = birthday;
  35. }
  36. public String getGender() {
  37. return gender;
  38. }
  39. public void setGender(String gender) {
  40. this.gender = gender;
  41. }
  42. public String getAddress() {
  43. return address;
  44. }
  45. public void setAddress(String address) {
  46. this.address = address;
  47. }
  48. public List<Account> getAccountList() {
  49. return accountList;
  50. }
  51. public void setAccountList(List<Account> accountList) {
  52. this.accountList = accountList;
  53. }
  54. @Override
  55. public String toString() {
  56. return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", gender='"
  57. + gender + '\'' + ", address='" + address + '\'' + ", accountList=" + accountList + '}';
  58. }
  59. }
  • AccountMapper.java
  1. package com.github.mapper;
  2. import com.github.entity.Account;
  3. import org.apache.ibatis.annotations.Mapper;
  4. import org.apache.ibatis.annotations.Result;
  5. import org.apache.ibatis.annotations.Results;
  6. import org.apache.ibatis.annotations.Select;
  7. /**
  8. * @author 许大仙
  9. * @version 1.0
  10. * @since 2021-11-02 10:45
  11. */
  12. @Mapper
  13. public interface AccountMapper {
  14. @Select("SELECT * FROM `account` where user_id = #{userId}")
  15. @Results({
  16. @Result(id = true, property = "id", column = "id"),
  17. @Result(property = "money", column = "money")}
  18. )
  19. List<Account> findByUserId(Integer userId);
  20. }
  • UserMapper.java
  1. package com.github.mapper;
  2. import com.github.entity.User;
  3. import org.apache.ibatis.annotations.*;
  4. import java.util.List;
  5. /**
  6. * @author 许大仙
  7. * @version 1.0
  8. * @since 2021-11-02 10:45
  9. */
  10. @Mapper
  11. public interface UserMapper {
  12. @Select(" SELECT * FROM `user`")
  13. @Results({
  14. @Result(id = true, property = "id", column = "id"),
  15. @Result(property = "username", column = "username"),
  16. @Result(property = "birthday", column = "birthday"),
  17. @Result(property = "gender", column = "gender"),
  18. @Result(property = "address", column = "address"),
  19. @Result(
  20. property = "accountList", // 被包含对象的变量名
  21. column = "id", // 根据查询出来的user表中的id去根据user_id查询
  22. many = @Many(select = "com.github.mapper.AccountMapper.findByUserId")),
  23. })
  24. List<User> findAll();
  25. }
  • 测试:
  1. package com.github.mybatis;
  2. import com.github.entity.User;
  3. import com.github.mapper.UserMapper;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. import org.junit.After;
  9. import org.junit.Before;
  10. import org.junit.Test;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.util.List;
  14. /**
  15. * @author 许大仙
  16. * @version 1.0
  17. * @since 2021-10-29 14:19
  18. */
  19. public class MybatisTest {
  20. SqlSession sqlSession;
  21. @Before
  22. public void before() throws IOException {
  23. // 使用Mybatis的Resources读取mybatis-config.xml配置文件
  24. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
  25. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  26. sqlSession = sqlSessionFactory.openSession();
  27. }
  28. @Test
  29. public void test() throws IOException {
  30. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  31. List<User> userList = userMapper.findAll();
  32. userList.forEach(System.out::println);
  33. }
  34. @After
  35. public void after() {
  36. if (null != sqlSession) {
  37. sqlSession.close();
  38. }
  39. }
  40. }

第六章:Mybatis 注解实现多对多关联查询

  • 多对多模型:

多对多模型.png

  • 查询学生的同时查询课程的信息对应的 SQL :
  1. SELECT * FROM `student`
  1. SELECT c.* FROM `student_course` sc INNER JOIN `course` c ON sc.cid = c.id WHERE sc.sid = #{id}
  • 示例:
  • Student.java
  1. package com.github.entity;
  2. import java.io.Serializable;
  3. import java.util.List;
  4. /**
  5. * @author 许大仙
  6. * @version 1.0
  7. * @since 2021-11-02 11:06
  8. */
  9. public class Student implements Serializable {
  10. private Integer id;
  11. private String name;
  12. private Integer age;
  13. private List<Course> courseList;
  14. public Student() {}
  15. public Student(Integer id, String name, Integer age, List<Course> courseList) {
  16. this.id = id;
  17. this.name = name;
  18. this.age = age;
  19. this.courseList = courseList;
  20. }
  21. public Integer getId() {
  22. return id;
  23. }
  24. public void setId(Integer id) {
  25. this.id = id;
  26. }
  27. public String getName() {
  28. return name;
  29. }
  30. public void setName(String name) {
  31. this.name = name;
  32. }
  33. public Integer getAge() {
  34. return age;
  35. }
  36. public void setAge(Integer age) {
  37. this.age = age;
  38. }
  39. @Override
  40. public String toString() {
  41. return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", courseList=" + courseList + '}';
  42. }
  43. }
  • Course.java
  1. package com.github.entity;
  2. import java.io.Serializable;
  3. /**
  4. * @author 许大仙
  5. * @version 1.0
  6. * @since 2021-11-02 11:07
  7. */
  8. public class Course implements Serializable {
  9. private Integer id;
  10. private String name;
  11. public Course() {}
  12. public Integer getId() {
  13. return id;
  14. }
  15. public void setId(Integer id) {
  16. this.id = id;
  17. }
  18. public String getName() {
  19. return name;
  20. }
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24. @Override
  25. public String toString() {
  26. return "Course{" + "id=" + id + ", name='" + name + '\'' + '}';
  27. }
  28. }
  • CourseMapper.java
  1. package com.github.mapper;
  2. import com.github.entity.Course;
  3. import org.apache.ibatis.annotations.Mapper;
  4. import org.apache.ibatis.annotations.Select;
  5. import java.util.List;
  6. /**
  7. * @author 许大仙
  8. * @version 1.0
  9. * @since 2021-11-02 11:09
  10. */
  11. @Mapper
  12. public interface CourseMapper {
  13. @Select("SELECT c.* FROM `student_course` sc INNER JOIN `course` c ON sc.cid = c.id WHERE sc.sid = #{id}")
  14. List<Course> findBySid(Integer id);
  15. }
  • StudentMapper.java
  1. package com.github.mapper;
  2. import com.github.entity.Student;
  3. import org.apache.ibatis.annotations.*;
  4. import java.util.List;
  5. /**
  6. * @author 许大仙
  7. * @version 1.0
  8. * @since 2021-11-02 11:09
  9. */
  10. @Mapper
  11. public interface StudentMapper {
  12. @Select("SELECT * FROM `student`")
  13. @Results({
  14. @Result(id = true, property = "id", column = "id"),
  15. @Result(property = "name", column = "name"),
  16. @Result(property = "age", column = "age"),
  17. @Result(
  18. property = "courseList", //被包含对象的变量名
  19. column = "id", //根据查询出来的student表中的id去中间表和course表中查询
  20. many = @Many(select = "com.github.mapper.CourseMapper.findBySid")
  21. )
  22. })
  23. List<Student> findAll();
  24. }
  • 测试:
  1. package com.github.mybatis;
  2. import com.github.entity.Student;
  3. import com.github.mapper.StudentMapper;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. import org.junit.After;
  9. import org.junit.Before;
  10. import org.junit.Test;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.util.List;
  14. /**
  15. * @author 许大仙
  16. * @version 1.0
  17. * @since 2021-10-29 14:19
  18. */
  19. public class MybatisTest {
  20. SqlSession sqlSession;
  21. @Before
  22. public void before() throws IOException {
  23. // 使用Mybatis的Resources读取mybatis-config.xml配置文件
  24. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
  25. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  26. sqlSession = sqlSessionFactory.openSession();
  27. }
  28. @Test
  29. public void test() throws IOException {
  30. StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
  31. List<Student> studentList = studentMapper.findAll();
  32. studentList.forEach(System.out::println);
  33. }
  34. @After
  35. public void after() {
  36. if (null != sqlSession) {
  37. sqlSession.close();
  38. }
  39. }
  40. }