• JAVA mybatis操作mysql——批量增加,批量删除,多条件模糊搜索,新增时返回id和常用的增删查改


    目录

    1 Moven配置文件

    2 mybatis.xml

    3 实体类

    4 SqlSessionUtils工具类 

    5 UserMapper.xml文件 

    6 UserMapper接口

    7 UserMapperTest测试类 

    8 表SQL文件 

    9 项目结构 

    10 将数据库配置从mybatis中抽离出来 

    11 关系(一对一,一对多,多对多)

    12 注解开发 

    13 一级二级缓存


    自己写个清单,比较基础但是也可能有不对的地方

    1 Moven配置文件

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.mybatisgroupId>
    4. <artifactId>mybatisartifactId>
    5. <version>3.5.11version>
    6. dependency>
    7. <dependency>
    8. <groupId>mysqlgroupId>
    9. <artifactId>mysql-connector-javaartifactId>
    10. <version>8.0.28version>
    11. dependency>
    12. <dependency>
    13. <groupId>junitgroupId>
    14. <artifactId>junitartifactId>
    15. <version>RELEASEversion>
    16. <scope>testscope>
    17. dependency>
    18. dependencies>
    19. <build>
    20. <resources>
    21. <resource>
    22. <directory>src/main/javadirectory>
    23. <includes>
    24. <include>**/*.propertiesinclude>
    25. <include>**/*.xmlinclude>
    26. includes>
    27. <filtering>truefiltering>
    28. resource>
    29. <resource>
    30. <directory>src/main/resourcesdirectory>
    31. <includes>
    32. <include>**/*.propertiesinclude>
    33. <include>**/*.xmlinclude>
    34. includes>
    35. <filtering>truefiltering>
    36. resource>
    37. resources>
    38. build>

    2 mybatis.xml

    1. "1.0" encoding="UTF-8" ?>
    2. 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" value="jdbc:mysql://localhost:3306/mybatis"/>
    12. <property name="username" value="root"/>
    13. <property name="password" value="scm13503905942"/>
    14. dataSource>
    15. environment>
    16. environments>
    17. <mappers>
    18. <package name="com.learn.mapper"/>
    19. mappers>
    20. configuration>

    3 实体类

    User实体类

    1. package com.learn.entity;
    2. import java.util.Date;
    3. import java.util.List;
    4. public class User {
    5. private Integer id;
    6. private String username;// 用户姓名
    7. private String sex;// 性别
    8. private Date birthday;// 生日
    9. private String address;// 地址
    10. public User() {
    11. }
    12. public User(Integer id, String username, String sex, Date birthday, String address) {
    13. this.id = id;
    14. this.username = username;
    15. this.sex = sex;
    16. this.birthday = birthday;
    17. this.address = address;
    18. }
    19. /**
    20. * 获取
    21. * @return id
    22. */
    23. public Integer getId() {
    24. return id;
    25. }
    26. /**
    27. * 设置
    28. * @param id
    29. */
    30. public void setId(Integer id) {
    31. this.id = id;
    32. }
    33. /**
    34. * 获取
    35. * @return username
    36. */
    37. public String getUsername() {
    38. return username;
    39. }
    40. /**
    41. * 设置
    42. * @param username
    43. */
    44. public void setUsername(String username) {
    45. this.username = username;
    46. }
    47. /**
    48. * 获取
    49. * @return sex
    50. */
    51. public String getSex() {
    52. return sex;
    53. }
    54. /**
    55. * 设置
    56. * @param sex
    57. */
    58. public void setSex(String sex) {
    59. this.sex = sex;
    60. }
    61. /**
    62. * 获取
    63. * @return birthday
    64. */
    65. public Date getBirthday() {
    66. return birthday;
    67. }
    68. /**
    69. * 设置
    70. * @param birthday
    71. */
    72. public void setBirthday(Date birthday) {
    73. this.birthday = birthday;
    74. }
    75. /**
    76. * 获取
    77. * @return address
    78. */
    79. public String getAddress() {
    80. return address;
    81. }
    82. /**
    83. * 设置
    84. * @param address
    85. */
    86. public void setAddress(String address) {
    87. this.address = address;
    88. }
    89. public String toString() {
    90. return "User{id = " + id + ", username = " + username + ", sex = " + sex + ", birthday = " + birthday + ", address = " + address + "}";
    91. }
    92. }

    UserExt实体类

    1. package com.learn.entity;
    2. //如果传入的参数够多,可以将参数再包装一次
    3. public class UserExt {
    4. private User user;
    5. private String characteristic;
    6. public UserExt() {
    7. }
    8. public UserExt(User user, String characteristic) {
    9. this.user = user;
    10. this.characteristic = characteristic;
    11. }
    12. /**
    13. * 获取
    14. * @return user
    15. */
    16. public User getUser() {
    17. return user;
    18. }
    19. /**
    20. * 设置
    21. * @param user
    22. */
    23. public void setUser(User user) {
    24. this.user = user;
    25. }
    26. /**
    27. * 获取
    28. * @return characteristic
    29. */
    30. public String getCharacteristic() {
    31. return characteristic;
    32. }
    33. /**
    34. * 设置
    35. * @param characteristic
    36. */
    37. public void setCharacteristic(String characteristic) {
    38. this.characteristic = characteristic;
    39. }
    40. public String toString() {
    41. return "UserExt{user = " + user + ", characteristic = " + characteristic + "}";
    42. }
    43. }

    4 SqlSessionUtils工具类 

    1. package com.learn.utils;
    2. import org.apache.ibatis.io.Resources;
    3. import org.apache.ibatis.session.SqlSession;
    4. import org.apache.ibatis.session.SqlSessionFactory;
    5. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    6. import java.io.IOException;
    7. import java.io.InputStream;
    8. public class SqlSessionUtils {
    9. static SqlSessionFactory sqlSessionFactory;
    10. static {
    11. String path = "mybatis.xml";
    12. InputStream ins = null;
    13. try {
    14. ins = Resources.getResourceAsStream(path);
    15. } catch (IOException e) {
    16. throw new RuntimeException(e);
    17. }
    18. sqlSessionFactory = new SqlSessionFactoryBuilder().build(ins);
    19. }
    20. public static SqlSession getSqlSes() {
    21. return sqlSessionFactory.openSession();
    22. }
    23. public static void closeSqlSes(SqlSession sqlSession) {
    24. if (sqlSession != null) {
    25. sqlSession.close();
    26. }
    27. }
    28. }

    5 UserMapper.xml文件 

    1. "1.0" encoding="UTF-8"?>
    2. mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.learn.mapper.UserMapper">
    6. <select id="selectUserById" resultType="com.learn.entity.User">
    7. select * from user
    8. <where>
    9. id=#{id}
    10. where>
    11. select>
    12. <select id="selectUserBySexAndAddress" resultType="com.learn.entity.User">
    13. select *
    14. from user
    15. where sex = #{sex}
    16. and address = #{address}
    17. select>
    18. <select id="selectUserByUserNameAndSexDim" resultType="com.learn.entity.User">
    19. select * from user
    20. <where>
    21. <if test="null!=username">
    22. and username like concat('%',#{username},'%')
    23. if>
    24. <if test="null!=sex">
    25. and sex like concat('%',#{sex},'%')
    26. if>
    27. where>
    28. select>
    29. <select id="selectAll" resultType="com.learn.entity.User">
    30. select *
    31. from user
    32. select>
    33. <select id="selectUserBySexAndNameDim2" parameterType="com.learn.entity.UserExt" resultType="com.learn.entity.User">
    34. select * from user
    35. <where>
    36. <if test="null!=user.sex">
    37. and sex like '%${user.sex}%'
    38. if>
    39. <if test="null!=user.username">
    40. and username like '%${user.username}%'
    41. if>
    42. where>
    43. select>
    44. <update id="updateUser" parameterType="com.learn.entity.User">
    45. update user
    46. <set>
    47. <if test="username!=null">
    48. username=#{username},
    49. if>
    50. <if test="username!=null">
    51. birthday=#{birthday},
    52. if>
    53. <if test="sex!=null">
    54. sex=#{sex},
    55. if>
    56. <if test="address!=null">
    57. address=#{address}
    58. if>
    59. set>
    60. where id=#{id}
    61. update>
    62. <insert id="insertUser" parameterType="com.learn.entity.User" useGeneratedKeys="true" keyProperty="AffeectIdList">
    63. insert into user(id, username, birthday, sex, address)
    64. values (#{id}, #{username}, #{birthday}, #{sex}, #{address})
    65. <selectKey keyProperty="id" order="AFTER" resultType="int">
    66. SELECT LAST_INSERT_ID()
    67. selectKey>
    68. insert>
    69. <insert id="insertMultitudeUser" parameterType="com.learn.entity.User">
    70. insert into user(id, username, birthday, sex, address)
    71. values
    72. <foreach collection="list" separator="," item="item">
    73. (null, #{item.username}, #{item.birthday}, #{item.sex}, #{item.address})
    74. foreach>
    75. insert>
    76. <delete id="removeUserById" parameterType="int">
    77. delete
    78. from user
    79. <where>
    80. id = #{id}
    81. where>
    82. delete>
    83. mapper>

    6 UserMapper接口

    1. package com.learn.mapper;
    2. import com.learn.entity.User;
    3. import com.learn.entity.UserExt;
    4. import org.apache.ibatis.annotations.Param;
    5. import java.util.List;
    6. public interface UserMapper {
    7. //通过id查询
    8. User selectUserById(int userId);
    9. //通过性别和地址查询
    10. List selectUserBySexAndAddress(@Param("sex") String sex, @Param("address") String address);
    11. //通过用户名和性别模糊查询
    12. List selectUserByUserNameAndSexDim(@Param("username") String userName,@Param("sex") String sex);
    13. //通过传递包装类模糊查询
    14. List selectUserBySexAndNameDim2(UserExt userExt);
    15. //查询所有
    16. List selectAll();
    17. //修改
    18. int updateUser(User user);
    19. //插入数据,返回插入id
    20. int insertUser(User user);
    21. //删除
    22. int removeUserById(int userId);
    23. //批量插入
    24. int insertMultitudeUser(List user);
    25. //批量删除
    26. int removeMultitudeUser(int[] userIdArr);
    27. }

    7 UserMapperTest测试类 

    1. package com.learn.test;
    2. import com.learn.entity.User;
    3. import com.learn.entity.UserExt;
    4. import com.learn.mapper.UserMapper;
    5. import com.learn.utils.SqlSessionUtils;
    6. import org.apache.ibatis.session.SqlSession;
    7. import org.junit.AfterClass;
    8. import org.junit.BeforeClass;
    9. import org.junit.Test;
    10. import java.util.ArrayList;
    11. import java.util.Date;
    12. import java.util.List;
    13. public class UserMapperTest {
    14. static SqlSession session ;
    15. //在所有测试方法执行之前执行(只执行一次)
    16. @BeforeClass
    17. public static void init() {
    18. System.out.println("初始化完成!");
    19. session=SqlSessionUtils.getSqlSes();
    20. }
    21. //在所有测试方法执行完成之后执行(只执行一次)
    22. @AfterClass
    23. public static void end()
    24. {
    25. SqlSessionUtils.closeSqlSes(session);
    26. }
    27. @Test
    28. public void testSelectUserById() {
    29. UserMapper userMapper = session.getMapper(UserMapper.class);
    30. User user = userMapper.selectUserById(10);
    31. System.out.println("根据ID查询");
    32. System.out.println(user.toString());
    33. }
    34. @Test
    35. public void testSelectUserBySexAndAddress() {
    36. UserMapper userMapper = session.getMapper(UserMapper.class);
    37. userMapper.selectAll();
    38. List users = userMapper.selectUserBySexAndAddress("女","河南郑州");
    39. System.out.println("根据性别和地址查询");
    40. for (User user : users) {
    41. System.out.println(user.toString());
    42. }
    43. }
    44. @Test
    45. public void testselectUserByUserNameAndSexDim() {
    46. UserMapper userMapper = session.getMapper(UserMapper.class);
    47. List users = userMapper.selectUserByUserNameAndSexDim("孙","男");
    48. System.out.println("根据查询用户名和性别模糊查询");
    49. for (User user : users) {
    50. System.out.println(user.toString());
    51. }
    52. }
    53. @Test
    54. public void testselectUserBySexAndNameDim2() {
    55. UserMapper userMapper = session.getMapper(UserMapper.class);
    56. UserExt userExt=new UserExt(new User(null,"孙悟空","男",new Date(),"手机鞥"),"火");
    57. List users = userMapper.selectUserBySexAndNameDim2(userExt);
    58. System.out.println("通过传递包装类的方式根据查询用户名和性别模糊查询");
    59. users.forEach(System.out::println);
    60. }
    61. @Test
    62. public void testSelectAll()
    63. {
    64. UserMapper userMapper = session.getMapper(UserMapper.class);
    65. List users = userMapper.selectAll();
    66. System.out.println("查询所有数据");
    67. for (User user : users) {
    68. System.out.println(user.toString());
    69. }
    70. }
    71. @Test
    72. public void testUpdateUser()
    73. {
    74. UserMapper userMapper = session.getMapper(UserMapper.class);
    75. User user=new User();
    76. user.setId(30);
    77. user.setSex("男");
    78. user.setUsername("微微");
    79. user.setBirthday(new Date());
    80. int row = userMapper.updateUser(user);
    81. //注意事务提交
    82. session.commit();
    83. System.out.println("更新数据");
    84. }
    85. @Test
    86. public void testInsertUser()
    87. {
    88. UserMapper userMapper = session.getMapper(UserMapper.class);
    89. User user = new User();
    90. user.setSex("女");
    91. user.setUsername("梦鸽");
    92. user.setBirthday(new Date());
    93. System.out.println("插入数据:"+userMapper.insertUser(user)+"条");
    94. session.commit();
    95. //注意这里,只有插入完成后必须通过对象.属性才能获取到新增id值
    96. System.out.println("插入数据的id为:"+user.getId());
    97. }
    98. @Test
    99. public void testInsertMultitudeUser()
    100. {
    101. UserMapper userMapper = session.getMapper(UserMapper.class);
    102. List userList=new ArrayList<>();
    103. userList.add(new User(null,"分割","男",new Date(),"七彩祥云1号楼"));
    104. userList.add(new User(null,"茶几上的","男",new Date(),"七彩祥云2号楼"));
    105. userList.add(new User(null,"所开发的","男",new Date(),"七彩祥云3号楼"));
    106. userList.add(new User(null,"哦怕","男",new Date(),"七彩祥云4号楼"));
    107. userList.add(new User(null,"说的","男",new Date(),"七彩祥云5号楼"));
    108. int row=userMapper.insertMultitudeUser(userList);
    109. session.commit();
    110. System.out.println("批量插入数据:"+row+"条");
    111. }
    112. @Test
    113. public void testRemoveUserById()
    114. {
    115. UserMapper userMapper = session.getMapper(UserMapper.class);
    116. int row = userMapper.removeUserById(36);
    117. session.commit();
    118. System.out.println("删除数据:"+row+"条");
    119. }
    120. @Test
    121. public void testRemoveMultitudeUser()
    122. {
    123. List idArray = new ArrayList();
    124. idArray.add(30);
    125. idArray.add(31);
    126. idArray.add(32);
    127. UserMapper userMapper = session.getMapper(UserMapper.class);
    128. for (Integer integer : idArray) {
    129. userMapper.removeUserById(integer);
    130. }
    131. session.commit();
    132. System.out.println("删除数据"+idArray.size()+"条");
    133. }
    134. }

    8 表SQL文件 

    1. SET NAMES utf8mb4;
    2. SET FOREIGN_KEY_CHECKS = 0;
    3. -- ----------------------------
    4. -- Table structure for user
    5. -- ----------------------------
    6. DROP TABLE IF EXISTS `user`;
    7. CREATE TABLE `user` (
    8. `id` int(11) NOT NULL AUTO_INCREMENT,
    9. `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户名称',
    10. `birthday` date NULL DEFAULT NULL COMMENT '生日',
    11. `sex` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '性别',
    12. `address` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地址',
    13. PRIMARY KEY (`id`) USING BTREE
    14. ) ENGINE = InnoDB AUTO_INCREMENT = 48 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
    15. -- ----------------------------
    16. -- Records of user
    17. -- ----------------------------
    18. INSERT INTO `user` VALUES (1, '盛世名', NULL, '2', NULL);
    19. INSERT INTO `user` VALUES (10, '张三大牙', '2014-07-10', '女', '北京市');
    20. INSERT INTO `user` VALUES (16, '张吉东', NULL, '女', '河南郑州');
    21. INSERT INTO `user` VALUES (22, '孙训', NULL, '女', '河南郑州');
    22. INSERT INTO `user` VALUES (24, '周芷若', NULL, '女', '河南郑州');
    23. INSERT INTO `user` VALUES (28, '孙悟空', '2022-11-07', '男', '花果山1号');
    24. INSERT INTO `user` VALUES (29, '孙悟空', '2022-11-07', '男', '花果山1号');
    25. INSERT INTO `user` VALUES (33, '茶几上的', '2022-11-08', '男', '七彩祥云2号楼');
    26. INSERT INTO `user` VALUES (34, '所开发的', '2022-11-08', '男', '七彩祥云3号楼');
    27. INSERT INTO `user` VALUES (35, '哦怕', '2022-11-08', '男', '七彩祥云4号楼');
    28. INSERT INTO `user` VALUES (37, '梦鸽', '2022-11-08', '女', NULL);
    29. INSERT INTO `user` VALUES (38, '梦鸽', '2022-11-08', '女', NULL);
    30. INSERT INTO `user` VALUES (39, '梦鸽', '2022-11-08', '女', NULL);
    31. INSERT INTO `user` VALUES (41, '分割', '2022-11-08', '男', '七彩祥云1号楼');
    32. INSERT INTO `user` VALUES (42, '茶几上的', '2022-11-08', '男', '七彩祥云2号楼');
    33. INSERT INTO `user` VALUES (43, '所开发的', '2022-11-08', '男', '七彩祥云3号楼');
    34. INSERT INTO `user` VALUES (44, '哦怕', '2022-11-08', '男', '七彩祥云4号楼');
    35. INSERT INTO `user` VALUES (45, '说的', '2022-11-08', '男', '七彩祥云5号楼');
    36. INSERT INTO `user` VALUES (47, '梦鸽', '2022-11-08', '女', NULL);
    37. SET FOREIGN_KEY_CHECKS = 1;

    9 项目结构 

    10 将数据库配置从mybatis中抽离出来 

    在resources中新建一个db.properties配置文件

     里面粘贴上如下代码

    1. jdbc.driveClassName=com.mysql.cj.jdbc.Driver
    2. jdbc.url=jdbc:mysql://localhost:3306/mybatis
    3. jdbc.username=root
    4. jdbc.password=abc123123123

    然后替换原来的mybatis文件

    注意两个地方

    第1个是propeties标签的位置应该在environment标签之上

    第2个地方是替换数据库驱动中的那些value的内容,使用美元加大括号的方式

    1. "1.0" encoding="UTF-8" ?>
    2. configuration
    3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    5. <configuration>
    6. <properties resource="db.properties">
    7. properties>
    8. <environments default="development">
    9. <environment id="development">
    10. <transactionManager type="JDBC"/>
    11. <dataSource type="POOLED">
    12. <property name="driver" value="${jdbc.driveClassName}"/>
    13. <property name="url" value="${jdbc.url}"/>
    14. <property name="username" value="${jdbc.username}"/>
    15. <property name="password" value="${jdbc.password}"/>
    16. dataSource>
    17. environment>
    18. environments>
    19. <mappers>
    20. <package name="com.learn.mapper"/>
    21. mappers>
    22. configuration>

    11 关系(一对一,一对多,多对多)

    UserMapperTwo.xml

    1. "1.0" encoding="UTF-8"?>
    2. mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.learn.mapper.UserMapperTwo">
    6. <resultMap id="selectCartAndUserMap" type="com.learn.entity.Cart">
    7. <id column="cartId" property="cartId">id>
    8. <result column="userId" property="userId">result>
    9. <result column="totalnum" property="totalnum">result>
    10. <result column="totalmoney" property="totalmoney">result>
    11. <collection property="cartItem" ofType="com.learn.entity.CartItem">
    12. <id column="cartItemId" property="cartItemId">id>
    13. <result column="cartId" property="cartId">result>
    14. <result column="pid" property="pid">result>
    15. <result column="pnum" property="pnum">result>
    16. <result column="pmoney" property="pmoney">result>
    17. collection>
    18. resultMap>
    19. <select id="selectCartAndUser" resultMap="selectCartAndUserMap">
    20. select *
    21. from cart c,
    22. cartItem ci
    23. where c.cartId = ci.cartId
    24. select>
    25. <resultMap id="selectCartAndUserMap2" type="com.learn.entity.User">
    26. <id column="id" property="id">id>
    27. <result column="username" property="username">result>
    28. <result column="sex" property="sex">result>
    29. <result column="birthday" property="birthday">result>
    30. <result column="address" property="address">result>
    31. <association property="cart" javaType="com.learn.entity.Cart">
    32. <id column="cartId" property="cartId">id>
    33. <result column="userId" property="userId">result>
    34. <result column="totalnum" property="totalnum">result>
    35. <result column="totalmoney" property="totalmoney">result>
    36. association>
    37. resultMap>
    38. <select id="selectCartAndUser2" resultMap="selectCartAndUserMap2">
    39. select * from user u,cart c where u.id=c.cartId
    40. select>
    41. mapper>

    UserMapperTwo.java

    1. package com.learn.mapper;
    2. import com.learn.entity.User;
    3. import java.util.List;
    4. public interface UserMapperTwo {
    5. List selectCartAndUser();
    6. List selectCartAndUser2();
    7. }

    UserMapperTwoTest.java

    1. package com.learn.mapper;
    2. import com.learn.entity.User;
    3. import com.learn.utils.SqlSessionUtils;
    4. import org.apache.ibatis.session.SqlSession;
    5. import org.junit.AfterClass;
    6. import org.junit.BeforeClass;
    7. import org.junit.Test;
    8. import java.util.List;
    9. import static org.junit.Assert.*;
    10. public class UserMapperTwoTest {
    11. static SqlSession session ;
    12. //在所有测试方法执行之前执行(只执行一次)
    13. @BeforeClass
    14. public static void init() {
    15. System.out.println("初始化完成!");
    16. session= SqlSessionUtils.getSqlSes();
    17. }
    18. //在所有测试方法执行完成之后执行(只执行一次)
    19. @AfterClass
    20. public static void end()
    21. {
    22. SqlSessionUtils.closeSqlSes(session);
    23. }
    24. @Test
    25. public void selectCartAndUser()
    26. {
    27. UserMapperTwo userMapper = session.getMapper(UserMapperTwo.class);
    28. List users = userMapper.selectCartAndUser();
    29. System.out.println("1对多");
    30. for (int i = 0; i < users.size(); i++) {
    31. System.out.println(users.get(i));
    32. }
    33. }
    34. @Test
    35. public void selectSelectCartAndUser2() {
    36. UserMapperTwo userMapper = session.getMapper(UserMapperTwo.class);
    37. List users = userMapper.selectCartAndUser2();
    38. System.out.println("1对1");
    39. for (int i = 0; i < users.size(); i++) {
    40. System.out.println(users.get(i));
    41. }
    42. }
    43. }

     

    12 注解开发 

    UserMapperNotXml .java

    1. package com.learn.mapper;
    2. import com.learn.entity.User;
    3. import org.apache.ibatis.annotations.Select;
    4. public interface UserMapperNotXml {
    5. @Select("select * from user where id=#{id}")
    6. User selectUserById(int userId);
    7. }

    测试

    1. package com.learn.mapper;
    2. import com.learn.entity.User;
    3. import com.learn.utils.SqlSessionUtils;
    4. import org.apache.ibatis.session.SqlSession;
    5. import org.junit.AfterClass;
    6. import org.junit.BeforeClass;
    7. import org.junit.Test;
    8. import java.util.List;
    9. import static org.junit.Assert.*;
    10. public class UserMapperNotXmlTest {
    11. static SqlSession session ;
    12. //在所有测试方法执行之前执行(只执行一次)
    13. @BeforeClass
    14. public static void init() {
    15. System.out.println("初始化完成!");
    16. session= SqlSessionUtils.getSqlSes();
    17. }
    18. //在所有测试方法执行完成之后执行(只执行一次)
    19. @AfterClass
    20. public static void end()
    21. {
    22. SqlSessionUtils.closeSqlSes(session);
    23. }
    24. @Test
    25. public void TestselectUserById()
    26. {
    27. UserMapperNotXml userMapper = session.getMapper(UserMapperNotXml.class);
    28. User users = userMapper.selectUserById(10);
    29. System.out.println(users);
    30. }
    31. }

     

    13 一级二级缓存

    一级

    默认情况下,MyBatis 只开启一级缓存。

    是sqlSession级别的缓存 缓存的结构是个Map集合

    注意  由于 SqlSession 是相互隔离的,所以如果你使用不同的 SqlSession 对象,即使调用相同的 Mapper、参数和方法,MyBatis 还是会再次发送 SQL 到数据库执行,返回结果。

    二级

    二级缓存是全局缓存,作用域超出 session 范围之外,可以被所有同一个namespace内的 SqlSession 共享。

    打开二级缓存

    在mybatis.xml中配置

    1. "db.properties">
    2. "cacheEnabled" value="true" />
    3. default="development">

    使用

    1 在对应的maper里增加

     2 修改实体类

    3 测试

    4 补充

    局部不2级缓存 

    刷新2级缓存

     

     

  • 相关阅读:
    【Hello Algorithm】 暴力递归到动态规划 -- 总结
    Java静态代理模式
    Antv/G2 自定义折线图线条样式及tootip提示信息样式
    史上最全的字节跳动 Java 面试题集锦,高级 Java 工程师面试技术
    《数字图像处理-OpenCV/Python》连载:形态学图像处理
    一文掌握数仓中auto analyze的使用
    为什么好多政务网站以及高校网站没有安装SSL证书开启https?其实有免费专属SSL证书可用
    FLESH-DECT(MedIA 2021)——一个material decomposition的观点
    form表单基础
    #循循渐进学51单片机#函数进阶与按键#not.7
  • 原文地址:https://blog.csdn.net/qq_53679247/article/details/127758192