• JavaWeb开发-09-MyBatis


     官网:icon-default.png?t=N7T8https://mybatis.org/mybatis-3/zh/index.html

    一.Mybatis入门

    1.快速入门

     


    2.JDBC介绍


    3.数据库连接池

     官方地址:icon-default.png?t=N7T8https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter


    4.lombok

    二.Mybatis基础增删改查

    1.准备


    2.删除

     


    3.新增

     


    4.更新


    5.查询

    1. # 配置数据库的连接信息 - 四要素
    2. #驱动类名称
    3. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    4. #数据库连接的url
    5. spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
    6. #连接数据库的用户名
    7. spring.datasource.username=root
    8. #连接数据库的密码
    9. spring.datasource.password=1234
    10. # 配置mybatis的日志信息,指定到输出控制台
    11. mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    12. #开启mybatis的驼峰命名自动映射开关
    13. mybatis.configuration.map-underscore-to-camel-case=true
    1. package com.wjh.pojo;
    2. import lombok.AllArgsConstructor;
    3. import lombok.Data;
    4. import lombok.NoArgsConstructor;
    5. import java.time.LocalDate;
    6. import java.time.LocalDateTime;
    7. @Data
    8. @NoArgsConstructor
    9. @AllArgsConstructor
    10. public class Emp {
    11. private Integer id;
    12. private String username;
    13. private String password;
    14. private String name;
    15. private Short gender;
    16. private String image;
    17. private Short job;
    18. private LocalDate entrydate;
    19. private Integer deptId;
    20. private LocalDateTime createTime;
    21. private LocalDateTime updateTime;
    22. }
    1. package com.wjh.mapper;
    2. import com.wjh.pojo.Emp;
    3. import org.apache.ibatis.annotations.*;
    4. import java.time.LocalDate;
    5. import java.util.List;
    6. @Mapper
    7. public interface EmpMapper {
    8. //查询所有员工信息
    9. @Select("select * from emp")
    10. public List select();
    11. //根据ID删除员工信息操作
    12. @Delete("delete from emp where id = #{id}")
    13. //public void delete(Integer id);
    14. public int delete(Integer id);
    15. //新增员工
    16. @Options(useGeneratedKeys = true, keyProperty = "id")
    17. @Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time)" +
    18. "values (#{username}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime}) ")
    19. public void insert(Emp emp);
    20. //更新员工信息(修改)
    21. @Update("update emp set username = #{username}, name = #{name}, gender = #{gender}, image = #{image}, job = #{job}, entrydate = #{entrydate}, dept_id = #{deptId}, update_time = #{updateTime} where id = #{id};")
    22. public void update(Emp emp);
    23. //根据id查询用户信息
    24. @Select("select * from emp where id = #{id}")
    25. public Emp selectId(Integer id);
    26. // //方案一给字段起别名,让别名与实体名一致
    27. // @Select("select id, username, password, name, gender, image, job, entrydate, " +
    28. // "dept_id deptId, create_time createTime, update_time updateTime from emp where id = #{id}")
    29. // public Emp selectId2(Integer id);
    30. //
    31. // //方案二: 通过#@Result注解手动映射
    32. // @Results({
    33. // @Result(column = "dept_id",property = "deptId"),
    34. // @Result(column = "create_time",property = "createTome"),
    35. // @Result(column = "update_time",property = "updateTime")
    36. // })
    37. // @Select("select * from emp where id = #{id}")
    38. // public Emp selectId3(Integer id);
    39. //方案三: 开启mybatis的驼峰命名自动映射开关 -- a_column --------> aColumn
    40. //条件查询员工信息
    41. @Select("select * from emp where name like concat('%', #{name},'%') and gender = #{gender} " +
    42. "and entrydate between #{begin} and #{end} order by update_time desc")
    43. public List list(String name, Short gender, LocalDate begin, LocalDate end );
    44. // select concat('hello', 'mysql', 'word');
    45. // select * from emp where name like concat('%', '张', '%') and gender = '1' and
    46. // entrydate between '2010-01-01' and '2020-01-01' order by update_time desc;
    47. }

    1. package com.wjh;
    2. import com.wjh.mapper.EmpMapper;
    3. import com.wjh.pojo.Emp;
    4. import org.apache.ibatis.annotations.Mapper;
    5. import org.junit.jupiter.api.Test;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.boot.test.context.SpringBootTest;
    8. import java.time.LocalDate;
    9. import java.time.LocalDateTime;
    10. import java.util.ArrayList;
    11. import java.util.List;
    12. @SpringBootTest
    13. class SpringbootMybatisCrudApplicationTests {
    14. @Autowired
    15. private EmpMapper EmpMapper;
    16. //查询所有员工测试类
    17. @Test
    18. public void testListEmp(){
    19. List empList = EmpMapper.select();
    20. empList.stream().forEach(selectEmp -> {
    21. System.out.println(selectEmp);
    22. });
    23. }
    24. //根据id删除员工信息测试类
    25. @Test
    26. public void testDelete(){
    27. EmpMapper.delete(4);
    28. //int delete = EmpMapper.delete(4);
    29. //System.out.println("删除了" + delete + "条数据");
    30. testListEmp();
    31. }
    32. //新增员工测试类
    33. @Test
    34. public void testInsert(){
    35. Emp empInsert = new Emp();
    36. empInsert.setUsername("ikun6");
    37. empInsert.setName("坤坤6");
    38. empInsert.setGender((short)2);
    39. empInsert.setImage("#");
    40. empInsert.setJob((short)1);
    41. empInsert.setEntrydate(LocalDate.of(2000,01,01));
    42. empInsert.setDeptId(1);
    43. empInsert.setCreateTime(LocalDateTime.now());
    44. empInsert.setUpdateTime(LocalDateTime.now());
    45. //执行员工信息操作
    46. EmpMapper.insert(empInsert);
    47. System.out.println("主键:" + empInsert.getId());
    48. }
    49. //修改员工信息测试类
    50. @Test
    51. public void testUpdate(){
    52. Emp empUpdate = new Emp();
    53. empUpdate.setId(10);
    54. empUpdate.setUsername("zhaomingming");
    55. empUpdate.setName("赵敏");
    56. empUpdate.setGender((short)1);
    57. empUpdate.setImage("#");
    58. empUpdate.setJob((short)1);
    59. empUpdate.setEntrydate(LocalDate.of(2000,01,01));
    60. empUpdate.setDeptId(1);
    61. empUpdate.setUpdateTime(LocalDateTime.now());
    62. //执行员工信息操作
    63. EmpMapper.update(empUpdate);
    64. }
    65. //根据id查询用户信息测试类
    66. @Test
    67. public void testSelectId(){
    68. Emp emp = EmpMapper.selectId(10);
    69. System.out.println(emp);
    70. }
    71. //根据条件查询员工
    72. @Test
    73. public void testSelect(){
    74. EmpMapper.list("张", (short) 1, LocalDate.of(2010, 01, 01), LocalDate.of(2020, 01 , 01));
    75. }
    76. }

     三.Mybatis动态SQL

    1.XML映射文件

     

     

     

    1. //条件查询员工信息
    2. public List list(String name, Short gender, LocalDate begin, LocalDate end);
    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.wjh.mapper.EmpMapper">
    6. <select id="list" resultType="com.wjh.pojo.Emp">
    7. select *
    8. from emp
    9. where name like concat('%', #{name}, '%')
    10. and gender = #{gender}
    11. and entrydate between #{begin} and #{end}
    12. order by update_time desc
    13. select>
    14. mapper>
    1. //根据条件查询员工
    2. @Test
    3. public void testSelect(){
    4. List empList = EmpMapper.list("张", (short) 1,
    5. LocalDate.of(2010, 01, 01),
    6. LocalDate.of(2020, 01 , 01));
    7. System.out.println(empList);
    8. }

     

     

     

    官方说明icon-default.png?t=N7T8https://mybatis.net.cn/getting-started.html

     

    2.动态SQL

    (1).

     

     

    1. <select id="list" resultType="com.wjh.pojo.Emp">
    2. select *
    3. from emp
    4. <where>
    5. <if test="name != null">
    6. name like concat('%', #{name}, '%')
    7. if>
    8. <if test="gender != null">
    9. and gender = #{gender}
    10. if>
    11. <if test="begin != null and end != null">
    12. and entrydate between #{begin} and #{end}
    13. if>
    14. where>
    15. order by update_time desc
    16. select>

     

    1. //动态更新员工信息(修改)
    2. //@Update("update emp set username = #{username}, name = #{name}, gender = #{gender}, image = #{image}, job = #{job}, " +
    3. // "entrydate = #{entrydate}, dept_id = #{deptId}, update_time = #{updateTime} where id = #{id};")
    4. public void update2(Emp emp);

     

    1. <update id="update2">
    2. update emp
    3. <set>
    4. <if test="username != null">
    5. username = #{username},
    6. if>
    7. <if test="name != null">
    8. name = #{name},
    9. if>
    10. <if test="gender != null">
    11. gender = #{gender},
    12. if>
    13. <if test="image != null">
    14. image = #{image},
    15. if>
    16. <if test="job != null">
    17. job = #{job},
    18. if>
    19. <if test="entrydate != null">
    20. entrydate = #{entrydate},
    21. if>
    22. <if test="deptId != null">
    23. dept_id = #{deptId},
    24. if>
    25. <if test="updateTime != null">
    26. update_time = #{updateTime}
    27. if>
    28. set>
    29. where id = #{id}
    30. update>

     

    1. //动态更新员工信息-- 跟新id = 18 的员工 username 为 Tom11,name = 汤姆111, gander更新为2
    2. @Test
    3. public void testUpdate2(){
    4. //构造员工对象
    5. Emp emp = new Emp();
    6. emp.setId(19);
    7. emp.setUsername("tanmgu11");
    8. emp.setName("汤姆111");
    9. emp.setGender((short) 2);
    10. emp.setUpdateTime(LocalDateTime.now());
    11. //执行员工操作
    12. EmpMapper.update2(emp);
    13. }


    (2).

     

    1. //批量删除员工
    2. public void deleteByIds(List ids);
    1. <delete id="deleteByIds">
    2. delete from emp where id in
    3. <foreach collection="ids" item="id" separator="," open="(" close=")">
    4. #{id}
    5. foreach>
    6. delete>
    1. //批量删除员工
    2. @Test
    3. public void testdeleteByIds(){
    4. List list = Arrays.asList(16,17,18);
    5. EmpMapper.deleteByIds(list);
    6. }

    (3).

     

     

    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.wjh.mapper.EmpMapper">
    6. <sql id="commonSelect">
    7. select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time
    8. from emp
    9. sql>
    10. <select id="list" resultType="com.wjh.pojo.Emp">
    11. -- if
    12. <include refid="commonSelect" />
    13. <where>
    14. <if test="name != null">
    15. name like concat('%', #{name}, '%')
    16. if>
    17. <if test="gender != null">
    18. and gender = #{gender}
    19. if>
    20. <if test="begin != null and end != null">
    21. and entrydate between #{begin} and #{end},
    22. if>
    23. where>
    24. order by update_time desc
    25. select>
    26. <update id="update2">
    27. update emp
    28. <set>
    29. <if test="username != null">
    30. username = #{username},
    31. if>
    32. <if test="name != null">
    33. name = #{name},
    34. if>
    35. <if test="gender != null">
    36. gender = #{gender},
    37. if>
    38. <if test="image != null">
    39. image = #{image},
    40. if>
    41. <if test="job != null">
    42. job = #{job},
    43. if>
    44. <if test="entrydate != null">
    45. entrydate = #{entrydate},
    46. if>
    47. <if test="deptId != null">
    48. dept_id = #{deptId},
    49. if>
    50. <if test="updateTime != null">
    51. update_time = #{updateTime}
    52. if>
    53. set>
    54. where id = #{id}
    55. update>
    56. <delete id="deleteByIds">
    57. delete from emp where id in
    58. <foreach collection="ids" item="id" separator="," open="(" close=")">
    59. #{id}
    60. foreach>
    61. delete>
    62. mapper>

  • 相关阅读:
    FFmpeg直播能力更新计划与新版本发布
    如何彻底卸载mysql
    如何在Windows电脑上同时运行多个程序?
    关于POI包处理excel方法详解 (一)
    时间序列分解:将时间序列分解成基本的构建块
    不知道10年老电脑如何重装系统?其实很简单
    2022ICPC 网络赛第二场 B Non-decreasing Array(区间dp)
    .Net Core 实现WebSocket Server 的另外三种方式
    idea怎么快速查看所有断点
    电脑桌面文件删除了怎么恢复?分享3个技巧,你见过第3个吗?
  • 原文地址:https://blog.csdn.net/wangjh11234/article/details/133191484