MyBatis 增删改查

Dear 丶 2022-12-03 01:35 413阅读 0赞

对于 MyBatis 配置文件和映射文件基础不了解的可以下看看 ☞ MyBatis 详解

1.1 insert

1.1.1 新增单个

☞ DAO

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/9/1 * @description DAO */
  2. public interface StudentDao {
  3. public int insertOne(@Param("sex") String sex, @Param("name") String name, @Param("age") String age);
  4. }

☞ mapper

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.software.mybatis.controller.StudentDao">
  4. <!-- parameterType 指定插入的数据类型(可以省略),useGeneratedKeys 开启主键自增,keyProperty 指定主键 -->
  5. <insert id="insertOne" parameterType="student" useGeneratedKeys="true" keyProperty="id">
  6. insert into student values(null, #{name}, #{age}, #{sex})
  7. </insert>
  8. </mapper>

☞ 核心配置

  1. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
  2. <configuration>
  3. <typeAliases>
  4. <package name="com.software.mybatis.controller"/>
  5. </typeAliases>
  6. <environments default="development">
  7. <environment id="development">
  8. <transactionManager type="JDBC"/>
  9. <dataSource type="POOLED">
  10. <property name="driver" value="com.mysql.jdbc.Driver"/>
  11. <property name="url" value="jdbc:mysql://localhost:3306/db"/>
  12. <property name="username" value="root"/>
  13. <property name="password" value="root"/>
  14. </dataSource>
  15. </environment>
  16. </environments>
  17. <mappers>
  18. <mapper resource="student-mapper.xml"/>
  19. </mappers>
  20. </configuration>

☞ 测试类

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/9/1 * @description 测试类 */
  2. public class MybatisTest {
  3. @Test
  4. public void TestA() throws Exception {
  5. // 加载核心配置文件
  6. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
  7. // 获得 sqlSession 工厂对象
  8. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  9. // 获得 sqlSession 对象
  10. SqlSession sqlSession = sqlSessionFactory.openSession();
  11. // 数据准备
  12. Student student = new Student();
  13. student.setName("张三");
  14. student.setAge(23);
  15. student.setSex(false);
  16. // 执行 sql 语句
  17. int insert = sqlSession.insert("com.software.mybatis.controller.StudentDao.insertOne", student);
  18. // 打印结果
  19. System.out.println(insert);
  20. // 提交事务
  21. sqlSession.commit();
  22. // 释放资源
  23. sqlSession.close();
  24. }
  25. }

在这里插入图片描述

1.1.2 新增多个

☞ 动态 SQL 之 foreach

  如果需要插入多行数据要么操作多次进行插入,想要一次操作插入多行数据就需要使用动态 SQL 中的 foreach 了,其他配置与新增单个基本一致只需要修改 mapper 和 DAO 接口即可。

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/9/1 * @description 插入多行数据 */
  2. public interface StudentDao {
  3. public int insertList(List<Student> list);
  4. }

  foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及在迭代结果之间放置分隔符。这个元素是很智能的,因此它不会偶然地附加多余的分隔符。可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象传递给 foreach 作为集合参数。当使用可迭代对象或者数组时,index 是当前迭代的次数,item 的值是本次迭代获取的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.software.mybatis.controller.StudentDao">
  4. <insert id="insertList" useGeneratedKeys="true" keyProperty="id">
  5. insert into student values
  6. <foreach item="item" collection="list" separator=",">
  7. (null, #{item.name}, #{item.age}, #{item.sex})
  8. </foreach>
  9. </insert>
  10. </mapper>

☞ 测试

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/9/1 * @description 测试类 */
  2. public class MybatisTest {
  3. @Test
  4. public void TestA() throws Exception {
  5. // 加载核心配置文件
  6. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
  7. // 获得 sqlSession 工厂对象
  8. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  9. // 获得 sqlSession 对象
  10. SqlSession sqlSession = sqlSessionFactory.openSession();
  11. // 数据准备
  12. ArrayList<Student> list = new ArrayList<>();
  13. for (int i = 0; i < 5; i++) {
  14. Student student = new Student();
  15. student.setName("张三");
  16. student.setAge(23 + i);
  17. student.setSex(false);
  18. list.add(student);
  19. }
  20. // 执行 sql 语句
  21. int insert = sqlSession.insert("com.software.mybatis.controller.StudentDao.insertList", list);
  22. // 打印结果
  23. System.out.println(insert);
  24. // 提交事务
  25. sqlSession.commit();
  26. // 释放资源
  27. sqlSession.close();
  28. }
  29. }

在这里插入图片描述

1.2 delete

1.2.1 删除单个

☞ DAO

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/9/1 * @description DAO 接口 */
  2. public interface StudentDao {
  3. public int delOne(Long id);
  4. }

☞ mapper

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.software.mybatis.controller.StudentDao">
  4. <delete id="delOne" parameterType="long">
  5. delete from student where id = #{id}
  6. </delete>
  7. </mapper>

☞ 测试

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/9/1 * @description 测试类 */
  2. public class MybatisTest {
  3. @Test
  4. public void TestA() throws Exception {
  5. // 加载核心配置文件
  6. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
  7. // 获得 sqlSession 工厂对象
  8. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  9. // 获得 sqlSession 对象
  10. SqlSession sqlSession = sqlSessionFactory.openSession();
  11. // 执行 sql 语句
  12. int delRow = sqlSession.delete("com.software.mybatis.controller.StudentDao.delOne", 2L);
  13. // 打印结果
  14. System.out.println(delRow);
  15. // 提交事务
  16. sqlSession.commit();
  17. // 释放资源
  18. sqlSession.close();
  19. }
  20. }

在这里插入图片描述

1.2.2 IN

  利用 foreach 元素还可以使用 IN 运算符查询包含的数据。

☞ DAO

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/9/1 * @description DAO 接口 */
  2. public interface StudentDao {
  3. public int delList(List<Long> list);
  4. }

☞ mapper

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.software.mybatis.controller.StudentDao">
  4. <delete id="delList" parameterType="long">
  5. delete from student where id in
  6. <!-- open 前缀, close 后缀, separator 分隔符 -->
  7. <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
  8. #{item}
  9. </foreach>
  10. </delete>
  11. </mapper>

☞ 测试类

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/9/1 * @description 测试类 */
  2. public class MybatisTest {
  3. @Test
  4. public void TestA() throws Exception {
  5. // 加载核心配置文件
  6. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
  7. // 获得 sqlSession 工厂对象
  8. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  9. // 获得 sqlSession 对象
  10. SqlSession sqlSession = sqlSessionFactory.openSession();
  11. List<Long> list = new ArrayList<>();
  12. list.add(3L);
  13. list.add(4L);
  14. list.add(5L);
  15. // 执行 sql 语句
  16. int delRow = sqlSession.delete("com.software.mybatis.controller.StudentDao.delList", list);
  17. // 打印结果
  18. System.out.println(delRow);
  19. // 提交事务
  20. sqlSession.commit();
  21. // 释放资源
  22. sqlSession.close();
  23. }
  24. }

在这里插入图片描述

1.3 update

1.3.1 基本操作

  update 与 delete,insert 的操作类似

☞ DAO

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/9/1 * @description DAO 接口 */
  2. public interface StudentDao {
  3. public int update(@Param("name") String name, @Param("id") String id);
  4. }

☞ mapper

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.software.mybatis.controller.StudentDao">
  4. <update id="update">
  5. update student set name = #{name} where id = #{id}
  6. </update>
  7. </mapper>

☞ 测试类

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/9/1 * @description 测试类 */
  2. public class MybatisTest {
  3. @Test
  4. public void TestA() throws Exception {
  5. // 加载核心配置文件
  6. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
  7. // 获得 sqlSession 工厂对象
  8. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  9. // 获得 sqlSession 对象
  10. SqlSession sqlSession = sqlSessionFactory.openSession();
  11. // 修改数据
  12. Student student = new Student();
  13. student.setId(11L);
  14. student.setName("汪汪");
  15. // 执行 sql 语句
  16. int updateRow = sqlSession.update("com.software.mybatis.controller.StudentDao.update", student);
  17. // 打印结果
  18. System.out.println(updateRow);
  19. // 提交事务
  20. sqlSession.commit();
  21. // 释放资源
  22. sqlSession.close();
  23. }
  24. }

在这里插入图片描述

1.3.2 动态更新

  用于动态更新语句的解决方案叫做 set。set 元素可以用于动态包含需要更新的列,而舍去其它的。set 元素会动态前置 SET 关键字,同时也会删掉无关的逗号,因为用了条件语句之后很可能就会在生成的 SQL 语句的后面留下这些逗号。注意最后一个不要加 , 否则会有逗号遗留。

  1. <update id="update">
  2. update student
  3. <set>
  4. <if test="name != null">name=#{name},</if>
  5. <if test="age != null">age=#{age},</if>
  6. <if test="sex != null">sex=#{sex}</if>
  7. </set>
  8. where id=#{id}
  9. </update>

1.4 select

1.4.1 查询所有

☞ DAO

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/9/1 * @description DAO 接口 */
  2. public interface StudentDao {
  3. public List<Student> findAll();
  4. }

☞ mapper

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.software.mybatis.controller.StudentDao">
  4. <select id="findAll" resultType="student" >
  5. select * from student
  6. </select>
  7. </mapper>

☞ 测试类

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/9/1 * @description 测试类 */
  2. public class MybatisTest {
  3. @Test
  4. public void TestA() throws Exception {
  5. // 加载核心配置文件
  6. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
  7. // 获得 sqlSession 工厂对象
  8. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  9. // 获得 sqlSession 对象
  10. SqlSession sqlSession = sqlSessionFactory.openSession();
  11. // 执行 sql 语句
  12. List<Student> list = sqlSession.selectList("com.software.mybatis.controller.StudentDao.findAll");
  13. // 打印结果
  14. for (Student student : list) {
  15. System.out.println(student);
  16. }
  17. // 释放资源
  18. sqlSession.close();
  19. }
  20. }

在这里插入图片描述

1.4.2 打印 SQL 语句

  为了方便查看执行的条件查询,我们配置一下 log4j 日志

☞ 相关依赖

  1. <dependency>
  2. <groupId>log4j</groupId>
  3. <artifactId>log4j</artifactId>
  4. <version>1.2.17</version>
  5. </dependency>

☞ 配置文件(log4.properties)

  1. # 显示 SQL 语句
  2. log4j.logger.com.ibatis=DEBUG
  3. log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
  4. log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
  5. log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
  6. log4j.logger.Java.sql.Connection=DEBUG
  7. log4j.logger.java.sql.Statement=DEBUG
  8. log4j.logger.java.sql.PreparedStatement=DEBUG

☞ 配置 MyBatis

  1. <!-- 放到 properties 后 typeAliases 前 -->
  2. <settings>
  3. <setting name="logImpl" value="STDOUT_LOGGING"/>
  4. </settings>

1.4.3 动态 SQL 之 choose

☞ DAO

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/9/1 * @description DAO 接口 */
  2. public interface StudentDao {
  3. public List<Student> find(@Param("name") String name, @Param("age") Integer age);
  4. }

☞ mapper

  有时我们不想应用到所有的条件语句,而只想从中择其一项。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。提供了 name 就按照 name 查询,提供了 age 就按照 age 查询,若二者都没有提供就按照 sex 查询。二者都提供了谁在前面按照谁查询

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.software.mybatis.controller.StudentDao">
  4. <select id="find" resultType="student" >
  5. select * from student where 1 = 1
  6. <choose>
  7. <when test="name != null">
  8. AND name like #{name}
  9. </when>
  10. <when test="age != null">
  11. AND age = #{age}
  12. </when>
  13. <otherwise>
  14. AND sex = false
  15. </otherwise>
  16. </choose>
  17. </select>
  18. </mapper>

☞ 测试类

  1. /** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/9/1 * @description 测试类 */
  2. public class MybatisTest {
  3. @Test
  4. public void TestA() throws Exception {
  5. // 加载核心配置文件
  6. InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
  7. // 获得 sqlSession 工厂对象
  8. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
  9. // 获得 sqlSession 对象
  10. SqlSession sqlSession = sqlSessionFactory.openSession();
  11. Student stu = new Student();
  12. stu.setName("%汪%");
  13. stu.setAge(23);
  14. // 执行 sql 语句
  15. List<Student> list = sqlSession.selectList("com.software.mybatis.controller.StudentDao.find", stu);
  16. // 打印结果
  17. for (Student student : list) {
  18. System.out.println(student);
  19. }
  20. // 释放资源
  21. sqlSession.close();
  22. }
  23. }

在这里插入图片描述

1.4.4 动态 SQL 之 if

☞ mapper

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.software.mybatis.controller.StudentDao">
  4. <select id="find" resultType="student" >
  5. select * from student where 1 = 1
  6. <if test="name != null">
  7. AND name like #{name}
  8. </if>
  9. <if test="age != null">
  10. AND age = #{age}
  11. </if>
  12. </select>
  13. </mapper>

在这里插入图片描述

1.4.5 动态 SQL 之 where

  可以发现前面再拼接 SQL 是第一个是 1 = 1 这个恒成立的条件,这是因为可能会造成 select * from table where and name = name 的错误,MyBatis 提供了 where 元素会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入 where 子句。而且,若语句的开头为 and 或 or,where 元素也会将它们去除。

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.software.mybatis.controller.StudentDao">
  4. <select id="find" resultType="student" >
  5. select * from student
  6. <where>
  7. <if test="name != null">
  8. name like #{name}
  9. </if>
  10. <if test="age != null">
  11. AND age = #{age}
  12. </if>
  13. </where>
  14. </select>
  15. </mapper>

在这里插入图片描述

1.4.6 抽取 SQL 片段

  sql 标签可将重复的 SQL 提取出来,使用时用 include 引用即可,最终达到 SQL 重用的目的。

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.software.mybatis.controller.StudentDao">
  4. <sql id="selectStu">select * from student</sql>
  5. <select id="find" resultType="student" >
  6. <include refid="selectStu" ></include>
  7. <where>
  8. <if test="name != null">
  9. name like #{name}
  10. </if>
  11. <if test="age != null">
  12. AND age = #{age}
  13. </if>
  14. </where>
  15. </select>
  16. </mapper>

发表评论

表情:
评论列表 (有 0 条评论,413人围观)

还没有评论,来说两句吧...

相关阅读