MyBatis-Basic Operation-CRDU

Table of contents

Delete data according to id (D)

Add employee data (C)

Update Employee Information (U)

Modify employee information based on primary key

Query employee information (R)

 query by id

conditional query


The front-end page display provides data deletion operations, and the back-end implements it

Delete data according to id (D)

  • Concrete SQL statement
    • delete from emp where id =17;
  •  interface method
    •     @Delete("delete from emp where id =#{id} ")
          public int DeleteByID(Integer id);
  •  Test Methods
    •     @Test
          public void testDelete() {
              int delete = empMapper.DeleteByID(17);
              System.out.println(delete);
          }

Add employee data (C)

  •  Concrete SQL statement
    • insert into emp (username, name, gender, image, job, entrydate, dept_id, create_time, update_time)
      VALUES ('法老爷爷', '孙权', 1, '1.jpg', 1, '2021-06-13', 1, now(), now());
  • interface method

    •     @Insert("insert into emp (username, name, gender, image, job, entrydate, dept_id, create_time, update_time)" +
                  "VALUES (#{username}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime})")
          public void Insert(Emp emp);
    • In the Insert() method, if the parameter enp is passed in, then the #{} placeholder is used in the above SQL statement , and the name of the member variable in the emp object is filled in the placeholder to complete the transfer of the corresponding data

  • Test Methods

    •     @Test
          public void testInsert() {
              // 设置要插入的员工信息
              Emp emp = new Emp();
              emp.setUsername("法老爷爷");
              emp.setName("孙权");
              emp.setImage("1.jpg");
              emp.setGender((short) 1);
              emp.setJob((short) 1);
              emp.setEntrydate(LocalDate.of(2021, 12, 23));
              emp.setCreateTime(LocalDateTime.now());
              emp.setUpdateTime(LocalDateTime.now());
              emp.setDeptId(1);
      
              empMapper.Insert(emp);
      
          }
  • primary key returns

    • Description: After the data is added successfully, it is necessary to obtain the primary key of the data inserted into the database

    • Implementation: Add corresponding annotations to the interface, and then obtain the corresponding attribute where the primary key value is located in the test method

      •     @Options(useGeneratedKeys = true, keyProperty = "id")
            // 新增员工信息
            @Insert("insert into emp (username, name, gender, image, job, entrydate, dept_id, create_time, update_time)" +
                    "VALUES (#{username}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime})")
            public void Insert(Emp emp);
      • This annotation is a configuration in the Java Object Mapping (ORM) used to integrate with the MyBatis framework. Its meaning is as follows:

      • @Options: This is a MyBatis annotation used to specify some option configurations.
      • useGeneratedKeys = true: This option indicates whether MyBatis should use database-generated keys to populate the object's properties. When inserting a record, if the database automatically generates a primary key value, setting it  true will make MyBatis assign the value to the corresponding object's  id property.
      • To sum up, this annotation indicates that when performing an insert operation, the key generated by the database is used to populate the object's idproperty.

      • keyProperty = "id": This option specifies the object property name used to save the generated key value. In this example, the generated key values ​​will be assigned to the object's  id properties.
    • Test Methods
      •     @Test
            public void testInsert() {
                // 设置要插入的员工信息
                Emp emp = new Emp();
                emp.setUsername("法老20");
                emp.setName("孙权");
                emp.setImage("1.jpg");
                emp.setGender((short) 1);
                emp.setJob((short) 1);
                emp.setEntrydate(LocalDate.of(2021, 12, 23));
                emp.setCreateTime(LocalDateTime.now());
                emp.setUpdateTime(LocalDateTime.now());
                emp.setDeptId(1);
        
                empMapper.Insert(emp);
                System.out.println(emp.getId());
        
            }
      • The result of the operation is as follows

Update Employee Information (U)

Modify employee information based on primary key

  • SQL statement
    • -- todo 根据主键修改员工信息
      update emp
      set username   = '',
          name='',
          gender='',
          image='',
          job='',
          entrydate='',
          dept_id='',
          update_time=''
      where id = 1;
  • interface method

    •     @Update("update emp\n" +
                  "set username   = #{username},\n" +
                  "    name=#{name},\n" +
                  "    gender=#{gender},\n" +
                  "    image=#{image},\n" +
                  "    job=#{job},\n" +
                  "    entrydate=#{entrydate},\n" +
                  "    dept_id=#{deptId},\n" +
                  "    update_time=#{updateTime}\n" +
                  "where id = #{id};")
          public void Update(Emp emp);
  • Test Methods

    •     @Test
          public void testUpdate() {
              Emp emp = new Emp();
              emp.setId(18);
              emp.setUsername("TOM");
              emp.setName("汤姆");
              emp.setGender((short) 1);
              emp.setImage("1.jpg");
              emp.setJob((short) 1);
              emp.setEntrydate(LocalDate.of(2000, 1, 25));
              emp.setUpdateTime(LocalDateTime.now());
              emp.setDeptId(1);
      
              empMapper.Update(emp);
          }

Query employee information (R)

 query by id

  • SQL statement
    • select id,
             username,
             password,
             name,
             gender,
             image,
             job,
             entrydate,
             dept_id,
             create_time,
             update_time
      from emp
      where id = 5;
  • interface method

    •     @Select("select id,\n" +
                  "       username,\n" +
                  "       password,\n" +
                  "       name,\n" +
                  "       gender,\n" +
                  "       image,\n" +
                  "       job,\n" +
                  "       entrydate,\n" +
                  "       dept_id,\n" +
                  "       create_time,\n" +
                  "       update_time\n" +
                  "from emp\n" +
                  "where id = #{id};")
          public Emp SelectByID(Integer id);
  • Test Methods

    •     @Test
          public void testSelectByID() {
              Emp emp = empMapper.SelectByID(5);
              System.out.println(emp);
          }
      
  • operation result

    • In the above running results, the last three data are null, but in the database, these three data are all valuable, the solution to this problem will be mentioned below
  • MyBatis data encapsulation
    • The attribute name of the entity class is the same as the field name returned by the database table query , and mybatis will automatically encapsulate it
    • If the attribute name of the entity class is inconsistent with the field name returned by the database table query , it cannot be automatically encapsulated
      • solution
        • Solution 1: Alias ​​the field so that the alias is consistent with the attribute name in the entity class
        •     @Select("select id,\n" +
                      "       username,\n" +
                      "       password,\n" +
                      "       name,\n" +
                      "       gender,\n" +
                      "       image,\n" +
                      "       job,\n" +
                      "       entrydate,\n" +
                      "       dept_id     as deptId,\n" +
                      "       create_time as createTime,\n" +
                      "       update_time as updateTime\n" +
                      "from emp\n" +
                      "where id = #{id};")
              public Emp SelectByID(Integer id);
        • Solution 2: If @Results, @Result annotation manual mapping encapsulation

        •     @Results({
                      // column为字段名,property为对象的属性名
                      @Result(column = "dept_id", property = "deptId"),
                      @Result(column = "create_time", property = "createTime"),
                      @Result(column = "update_time", property = "updateTime")
              })
              @Select("select id,\n" +
                      "       username,\n" +
                      "       password,\n" +
                      "       name,\n" +
                      "       gender,\n" +
                      "       image,\n" +
                      "       job,\n" +
                      "       entrydate,\n" +
                      "       dept_id     ,\n" +
                      "       create_time ,\n" +
                      "       update_time \n" +
                      "from emp\n" +
                      "where id = #{id};")
              public Emp SelectByID(Integer id);
        • operation result

        • Common method : Turn on MyBatis hump naming automatic mapping switch

        • Using this method must strictly abide by the name of the field in the database named a_column, and the name of the attribute in the object is named aColumn, so that the mapping can be automatically completed
          • That is, automatically encapsulate the a_column field name into the aColumn attribute name

          • Configure in the configuration file

          • #数据库连接驱动
            spring.datasourde.driver-class-name=com.mysql.cj.jdbc.Driver
            # 数据库连接url
            spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
            # 数据库用户名
            spring.datasource.username=root
            # 数据库用户名密码
            spring.datasource.password=123456
            # 配置MyBatis日志,指定输出到控制台
            mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
            # 开启MyBatis的驼峰命名自动映射开关 a_column-->aColumn
            mybatis.configuration.map-underscore-to-camel-case=true
            

conditional query

  •  SQL statement
    • select id,
             username,
             password,
             name,
             gender,
             image,
             job,
             entrydate,
             dept_id,
             create_time,
             update_time
      from emp
      where name like '%张%'
        and gender = 1
        and entrydate between '2010-01-01' and '2020-01-01'
      order by update_time desc;
  • interface method

    •     @Select("select id,\n" +
                  "       username,\n" +
                  "       password,\n" +
                  "       name,\n" +
                  "       gender,\n" +
                  "       image,\n" +
                  "       job,\n" +
                  "       entrydate,\n" +
                  "       dept_id,\n" +
                  "       create_time,\n" +
                  "       update_time\n" +
                  "from emp\n" +
                  "where name like '%${name}%'\n" +
                  "  and gender = #{gender}\n" +
                  "  and entrydate between #{begin} and #{end}\n" +
                  "order by update_time desc;")
          public List<Emp> List(String name, short gender, LocalDate begin, LocalDate end);
    • Test Methods

      •     @Test
            public void TestList() {
                List<Emp> list = empMapper.List("张", (short) 1, LocalDate.of(2010, 01, 01), LocalDate.of(2020, 01, 01));
                System.out.println(list);
            }
    • operation result

In the above-mentioned interface method, the query condition for the name name is a fuzzy query, and the ${} placeholder is used. For the difference between #{} and ${}, please refer to the article: Detailed analysis of #{} and ${ } What is the difference?_Huangnichuan Water Monkey Blog-CSDN Blog

However, using the above ${} placeholders has low performance, insecurity, and SQL injection problems. The solutions are as follows

Use the concat function (string splicing function) in MySQL to solve

sample code

select concat('hello','MySQL')

The result of the operation is:

The code modification of the interface method in the above example is as follows:

 The result of the operation is as follows

Guess you like

Origin blog.csdn.net/weixin_64939936/article/details/132052104