Mybatis +MybatisPlus

1. Mybatis interface notes

1.1 Requirements

Mybatis data query has two kinds of Sql writing.

1. Write all Sql statements to the XML mapping file. (Universal operation mode)2. Sql statements can be annotated in interface methods (only applicable to simple operations).

    // Note: Mapping file or annotation is optional
    @Select("select * from demo_user where id = #{id}")
    User fidUserById(int id);
Copy the code

1.2 Types of annotations

Note: This annotation is generally simple to operate data queries, if you encounter associated query/complex Sql using Mapper mapping file is more general.

@Mapper// Spring creates a proxy object for this interface
public interface UserMapper {
    SQL > select * from user
    List<User> findAll(a);
    @Select("select * from demo_user where id = #{id}")
    @Insert("")/ / add
    @Update("")/ / update
    @Delete("")/ / delete
    }
Copy the code

1.3 Mybatis case exercise

1.3.1 Test method

@SpringBootTest
public class TestMybatis {

    // Specify: the injection must be an object
    // In order to integrate Mybatis, Spring simplifies the code structure dynamically for mybatis interface
    // Create a proxy object
    // Proxy: dynamically creates an instantiated object with the same functionality at run time, based on the original object model
    // Example: Sun Wukong (interface)/ clone an identical object
    @Autowired
    private UserMapper userMapper;

    @Test
    public void testFind(a){
        System.out.println(userMapper.getClass());
        List<User> userList = userMapper.findAll();
        System.out.println(userList);
    }

    // Query data by ID
    @Test
    public void findUserById(a){

       User user = userMapper.findUserById(11);
       System.out.println(user);
    }

    // Add a user
    // Where does the data come from dynamically
    @Test
    public void insert(a){
        User user = new User();
        user.setName("Friday").setSex("Male").setAge(18);
        userMapper.insert(user);
        System.out.println("New success");
    }
    // Change Friday's age to 20 and gender to female
    @Test
    public void update(a){
        User user = new User();
        user.setAge(20).setSex("Female").setName("Friday"); userMapper.updateByName(user); }}Copy the code

Mapper = Mapper = Mapper

package com.jt.mapper;

import com.jt.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper// Spring creates a proxy object for this interface
public interface UserMapper {
    SQL > select * from user
    List<User> findAll(a);
    @Select("select * from demo_user where id = #{id}")
    @Insert("")/ / add
    @Update("")/ / update
    @Delete("")/ / delete
    // Note: Mapping file or annotation is optional
    @Select("select * from demo_user where id = #{id}")
    User fidUserById(int id);
    @Insert("insert into demo_user (id ,name,age,sex) value (null,#{name},#{age},#{sex})")
    void insert (User user);
    @Update("update demo_user set age=#{age},sex=#{sex} where name=#{name}")
    void updateByName(User user);
}
Copy the code

2. MybatisPlus

2.1 MP is introduced

2.2 Why MP is used

Scene description: Xiao Hong is a 10 years development, a monthly salary of 1 million. This is the need for Xiaohong to develop a set of Beijing Tao projects to achieve the most commonly used CURD functions. Operations like this are simple and tedious. If a lot of code is written by programmers, it will affect the development efficiency. Requirements: Simple, tedious tasks like this are best left to the framework to automate. Note: USE MP to complete CRUD operations of forms and simplify the development process

2.3 MP Introduction case

1. Import JAR package 2. Use object to operate the database 3. Inherit the common interface, obtain common CRUD operations 5. Realize data operations.

2.3.1 Importing jar Packages

<! <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.43.</version>
        </dependency>
Copy the code

2.2.2 editor pojo

@tablename (“demo_user”)// implement object and TableName mapping 2. Implement primary key increment @tableID (type = idtype.auto) 3. Implement attribute and field mapping rules: omit @tableField (“name”) if attribute and field name match

@Data//ste/get/toString
@Accessors(chain = true)// chain loading
@TableName("demo_user")// Implement object and table name mapping
public class User {
    // Set primary key increment
    @TableId(type = IdType.AUTO)//ASSIGN_ID + ASSIGN_UUID
    private Integer id;
    @TableField("name")// Implement attribute and field mapping
    private String name;
    @TableField("age")
    private Integer age;
    @TableField("sex")
    private String sex;
}
Copy the code

2.2.3 Inheriting public Interfaces

Note: After inheriting the interface, you must add the generic object, otherwise the program can not execute the interface in the parent class :MP will be used to extract CRUD methods, later if the subclass needs to call, then directly extractConfigure the procedure interface file

public interface UserMapper extends BaseMapper<User> {
    List<User> findAll(a);
}
Copy the code

. Yml file

Mybatis -plus: # set alias package type-aliases-package: com.jt.pojo # load the mapping file mapper-locations: classpath:/mappers/*.xml
  #开启驼峰映射
  configuration:
    map-underscore-to-camel-case: true
#打印SQl语句
logging:
  level:
    com.jt.mapper: debug
Copy the code

2.4 Core idea: Operate database in the way of objects

Configuration:

  1. Edit the mapping between poJOs and data tables.
  2. Edit POJO properties and table field mappings.
  3. Encapsulates a number of commonly used CURD apis
  4. Dynamically generate Sql statements based on objects

Execution process:

  1. Usermapper.insert (user);
  2. A generic object that dynamically gets operations based on the Mapper interface. Public Interface UserMapper extends BaseMapper Public Interface UserMapper extends BaseMapper
  3. As long as the get object gets the table name, the field name. The value of the data
  4. Convert the object into a specific SQL, which is then handed over to Mybatis for execution

Usermapper. insert(user object) Sql: insert into table name (….) Values (data value……)

2.5 MP Common operations

2.5.1 Querying Information By ID

    //1. Query database by primary key
    @Test
    public void testSelect1(a){//SELECT id,name,age,sex FROM demo_user WHERE id=?
        User user = userMapper.selectById(1);
        System.out.println(user);//User(id=1, name= black, age=3000, sex= male)
    }
Copy the code

2.5.2 Querying selectList Information (1)

    // select * from 'sex' where 'sex' = 'male'
    @Test
    public void textselect2(a){
        User user = new User();
        user.setName("Joe").setSex("Male");
        // Create a condition constructor to encapsulate the WHERE condition
        // The implementation dynamically concatenates where conditions based on non-null attributes in the object
        // The default relationship link is and
        QueryWrapper queryWrapper=new QueryWrapper(user);
        List<User> userList=userMapper.selectList(queryWrapper);//SELECT id,name,age,sex FROM demo_user WHERE name=? AND sex=?
        System.out.println(userList);//[User(id=43, age=19, sex= male)]
    }
Copy the code

2.5.3 Querying selectList Information (2)

    Select * from user where name=" sex "and sex=" male"
    //Sql:SELECT id,name,age,sex FROM demo_user WHERE name=? AND sex=?
    @Test
    public void testselect3(a){
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("name"."Joe")
                .eq("sex"."Male");
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);//[User(id=43, age=19, sex= male)]
    }
Copy the code

2.5.4 Querying selectList Information (3)

    //4. Select * from age>18 where sex=" female
    // SQL :select * from demo_user where age >18 and sex=' female '
    >gt, 
      
       =ge, <=le,! =ne
      ,>
    @Test
    public void testselect4(a){
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.gt("age"."18")
                .eq("sex"."Female");
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }
Copy the code

2.5.5 Like Keyword

    / / 5. Like the keyword
    Select * from lik where name = '% Joe 'where name = '% Joe'
    Where name = '% Joe 'where name = '% Joe'
    @Test
    public void testselect5(a){
        QueryWrapper<User> queryWrapper = new QueryWrapper();
// queryWrapper. Like ("name", "Joe ");
        queryWrapper.likeLeft("name"."Joe");
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }
Copy the code

2.5.6 In Keyword

    SQL: select * fron demo_user where in(1,3,5,6) */
    @Test
    public void testselect6(a){
        Integer[] ids={1.3.5.6};
        // Ordinary arrays use wrapper types that use methods on objects. Basic types have no methods
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.in("id",ids);
        // Use variable parameter types to implement the query
        / / queryWrapper. In (" id ", 1,3,5,6,);
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }
Copy the code

2.5.7 Order by keyword

    /* * 标 签 :order by sort SQL: SELECT * from demo_user where sex=" male "order by age desc*/
    @Test
    public void testselect(a){
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("sex"."Male")
                .orderByDesc("name"."id" );
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }
Copy the code

Refer to the official website for more detailed operations

MyBatis – Plus website, https://mp.baomidou.com/guide/