MyBatis Plus-3-Universal CRUD

Keywords: Programming SQL Database Mybatis xml

General CRUD

1.1 Create the interface EmployeeMapper and inherit BaseMapper<T>

public interface EmployeeMapper extends BaseMapper<Employee> {
    /*
     * Mapper Interface
     *
     * Based on Mybatis: Writing CRUD-related methods in Mapper interface provides corresponding SQL mapping files and corresponding SQL statements for Mapper interface.
     *
     * MP-based: Let the XxxMapper interface inherit the BaseMapper interface.
     *
     * BaseMapper<T>:  Generics specify the type of entity class that the current Mapper interface operates on.
     *
     */

    //   Integer  insertEmployee(Employee employee );
    //   <insert useGeneratedKeys="true" keyProperty="id" > SQL...</insert>
}

2.1 Create test class TestMPCRUD01 for testing

2.1.1 Insert operation

public class TestMPCRUD01 {

    private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");

    private EmployeeMapper employeeMapper = ioc.getBean("employeeMapper", EmployeeMapper.class);

    @Test
    public void testCommonInsert() {
        //Initialize Employee objects
        Employee employee = new Employee();
        employee.setLastName("MP");
        employee.setEmail("mp@test.com");
        employee.setGender(1);
        employee.setAge(22);
        employee.setSalary(20000.0);
        // Insert into database
        // When insert method inserts, it makes non-null judgment according to each attribute of entity class. Only fields corresponding to non-null attributes appear in the SQL statement.
        // Integer result = employeeMapper.insert(employee);

        // When insertAllColumn method is inserted, the fields corresponding to the attributes will appear in the SQL statement regardless of whether the attributes are null or not.
        Integer result = employeeMapper.insertAllColumn(employee);

        System.out.println("result: " + result);

        //Get the primary key value of the current data in the database
        Integer key = employee.getId();
        System.out.println("key:" + key);
    }
}

2.1.2 Update Operation

    @Test
    public void testCommonUpdate() {
        //Initialization of Modified Objects
        Employee employee = new Employee();
        employee.setId(4);
        employee.setLastName("Miss Ozawa");
        employee.setEmail("xz@sina.com");
        employee.setGender(0);
        employee.setAge(33);

        //Integer result = employeeMapper.updateById(employee);
        Integer result = employeeMapper.updateAllColumnById(employee);

        System.out.println("result: " + result);
    }

2.1.3 Query Operations

    @Test
    public void testCommonSelect() {
        //1. Query by id
        Employee employee = employeeMapper.selectById(1);
        System.out.println(employee);

        //2. Query ID + lastName through multiple columns
        employee = new Employee();
        employee.setId(4);
        employee.setLastName("Miss Ozawa");
        employee.setGender(0);

        Employee result = employeeMapper.selectOne(employee);
        System.out.println("result: " + result);

        //3. Query <foreach> through multiple IDS
        List<Integer> idList = new ArrayList<>();
        idList.add(4);
        idList.add(5);
        idList.add(6);
        idList.add(7);

        List<Employee> emps = employeeMapper.selectBatchIds(idList);
        System.out.println(emps);

        //4. Encapsulating Conditions Query by Map
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("last_name", "Tom");
        columnMap.put("gender", 1);

        emps = employeeMapper.selectByMap(columnMap);
        System.out.println(emps);

        //5. Paging query
        emps = employeeMapper.selectPage(new Page<>(3, 2), null);
        System.out.println(emps);
    }

2.1.4 Delete operation

    @Test
    public void testCommonDelete() {
        //1. Delete according to id
        Integer result = employeeMapper.deleteById(13);
        System.out.println("result: " + result);

        //2. Delete according to conditions
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("last_name", "MP");
        columnMap.put("email", "mp@test.com");

        result = employeeMapper.deleteByMap(columnMap);
        System.out.println("result: " + result);

        //3. Batch deletion
        List<Integer> idList = new ArrayList<>();
        idList.add(3);
        idList.add(5);

        result = employeeMapper.deleteBatchIds(idList);
        System.out.println("result: " + result);
    }

3.1 summary

3.1.1 general purpose

Integer insert(T entity);
Integer insertAllColumn(T entity);

Integer updateById(@Param("et") T entity);
Integer updateAllColumnById(@Param("et") T entity);

T selectById(Serializable id);
T selectOne(@Param("ew") T entity);
List<T> selectBatchIds(List<? extends Serializable> idList);
List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
List<T> selectPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper);

Integer deleteById(Serializable id);
Integer deleteByMap(@Param("cm") Map<String, Object> columnMap);
Integer deleteBatchIds(List<? extends Serializable> idList);

3.1.2 Annotations/Global Configuration

@TableName
 Global MP configuration: <property name="tablePrefix" value="tbl_"></property>

@TableField
 Global MP configuration: <property name="dbColumn Underline" value="true"></property>

@TableId
 Global MP configuration: <property name="idType" value="0"></property>

Supporting primary key self-increment by inserting data into database to obtain primary key values
 Mybatis: You need to set it up with useGeneratedKeys and keyProperty
 MP: Automatically writes back primary key values to entity classes

4.1 SQL Injection Analysis

  • The essence of A. employeeMapper is org.apache.ibatis.binding.MapperProxy.
  • In B. Mapper Proxy, sqlSession -> SqlSession Factory.
  • C. SqlSession Facotry Configuration MappedStatements.
    • Each mappedStatement represents a method in the Mapper interface and an SQL in the Mapper mapping file.
    • When MP starts, it will analyze the methods in xxxMapper one by one, and process the corresponding SQL statements and save them to mappedStatements in the configuration object.
  • D. substance:
    • Configuration: MyBatis or MP global configuration objects.
    • MappedStatement: A MappedStatement object corresponds to a select/update/insert/delete node in the Mapper configuration file, which mainly describes an SQL statement.
    • SqlMethod: Enumeration of objects, SQL methods supported by MP.
    • TableInfo: The database table reflects information, so you can get information about the database table.
    • SqlSource: SQL statement processing objects.
    • Mapper Builder Assistant: Used for caching, SQL parameters, query prescription result set processing, etc. Each mappedStatement is added to mappedstatements in configuration through Mapper Builder Assistant.

Posted by callesson on Sat, 05 Oct 2019 18:08:08 -0700