springboot configuration MybatisPlus

Foreword:

Mybatis is still relatively popular in the persistence layer framework, and general projects are based on ssm. Although mybatis can directly operate the database through SQL statements in xml, it is very flexible. However, its operations are all carried out through SQL statements, so a large number of xml files must be written, which is very troublesome. mybatis-plus solves this problem very well.

1. Introduction to mybatis-plus:

Mybatis-Plus (MP for short) is an enhancement tool for Mybatis. Based on Mybatis, only enhancements are made without changes, and it was born to simplify development and improve efficiency. This is the official definition. For more introduction and features of mybatis-plus, please refer to the official website of mybatis-plus . So how is it enhanced? In fact, it has already encapsulated some crud methods, we don't need to write xml anymore, just call these methods directly, similar to JPA.

Second, spring integrates mybatis-plus:

As the official said, mybatis-plus only enhances and does not change on the basis of mybatis, so its integration with spring is also very simple. Just replace mybatis dependencies with mybatis-plus dependencies, and then replace sqlSessionFactory with mybatis-plus. Next, look at the specific operations:
1. pom.xml:
The core dependencies are as follows:

        <!-- spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.14.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <!-- mp 依赖 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>2.3</version>
        </dependency>

Note: These are core dependencies. This project also uses the mysql driver, c3p0, logs (slf4j-api, slf4j-log4j2), and lombok. To integrate mybatis-plus, remove mybatis and mybatis-spring to avoid conflicts; lombok is a tool, add this dependency, develop the tool and install the Lombok plug-in, and you can use it. The most common usage is to use it in entity classes The @Data annotation, so that the entity class does not need to write set, get, toString and other methods. For more usage of Lombok, please use Baidu.

2、log4j.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd
HH:mm:ss,SSS} %m (%F:%L) \n" />
        </layout>
    </appender>
    <logger name="java.sql">
        <level value="debug" />
    </logger>
    <logger name="org.apache.ibatis">
        <level value="info" />
    </logger>
    <root>
        <level value="debug" />
        <appender-ref ref="STDOUT" />
    </root>
</log4j:configuration>

3、jdbc.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///数据库名?useUnicode=true&characterEncoding=utf8
jdbc.username=#
jdbc.password=#

4、mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>

Note: Because it is integrated with spring, most of mybatis-plus is written in the spring configuration file. Here, just define an empty mybatis-config.xml.

5、spring-dao.xml:

<?xml version="1.0" encoding="UTF-8"?>    
<beans xmlns="http://www.springframework.org/schema/beans"    
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:aop="http://www.springframework.org/schema/aop"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:jee="http://www.springframework.org/schema/jee"  
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xsi:schemaLocation="    
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">    
        
    <!-- 配置整合mybatis-plus过程 -->
    <!-- 1、配置数据库相关参数properties的属性:${url} -->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <!-- 2、配置数据库连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!-- mybatis的sqlsessionFactorybean:org.mybatis.spring.SqlSessionFactoryBean-->
    <!-- 3、配置mybatis-plus的sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="typeAliasesPackage" value="com.zhu.mybatisplus.entity"/>
    </bean>
    <!-- 4、DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zhu.mybatisplus.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean> 
</beans>

6、entity:

@Data
@TableName(value = "tb_employee")//指定表名
public class Employee {
    //value与数据库主键列名一致,若实体类属性名与表主键列名一致可省略value
    @TableId(value = "id",type = IdType.AUTO)//指定自增策略
    private Integer id;
    //若没有开启驼峰命名,或者表中列名不符合驼峰规则,可通过该注解指定数据库表中的列名,exist标明数据表中有没有对应列
    @TableField(value = "last_name",exist = true)
    private String lastName;
    private String email;
    private Integer gender;
    private Integer age;
}

7、mapper:

public interface EmplopyeeDao extends BaseMapper<Employee> {
}

This completes the integration of mybatis-plus and spring. The first is to replace mybatis and mybatis-spring dependencies with mybatis-plus dependencies, then replace sqlsessionfactory with mybatis-plus, then add annotations such as @TableName, etc. to the entity class, and finally mapper inheritance .@TableIdBaseMapper

8. Test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml"})
public class test {
    @Autowired
    private DataSource dataSource;
    @Test
    public void testDataSource() throws SQLException {
        System.out.println(dataSource.getConnection());
    }
}

Run the junit, you can output the obtained connection, indicating that the integration is no problem:


All the codes in this article have been tested by myself, and this article involves a lot of codes. In order not to affect the length, no screenshots are taken where it is not necessary. All subsequent operations are based on this integrated project.
 

3. General crud of mp:

Requirements:
There is a tb_employee table, and there is already a corresponding entity class Employee. What do we need to do to realize the CRUD operation of the tb_employee table?
Based on Mybatis:
You need to write the EmployeeMapper interface, and manually write the sql statement corresponding to the CRUD method in the EmployeeMapper.xml mapping file.
Based on MP:
only need to create the EmployeeMapper interface, and inherit the BaseMapper interface.
We already have Employee, tb_employee, and EmployeeDao also inherits BaseMapper, and then use the crud method.

1. Insert operation:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml"})
public class test {
    @Autowired
    private EmplopyeeDao emplopyeeDao;
    @Test
    public void testInsert(){
        Employee employee = new Employee();
        employee.setLastName("东方不败");
        employee.setEmail("[email protected]");
        employee.setGender(1);
        employee.setAge(20);
        emplopyeeDao.insert(employee);
        //mybatisplus会自动把当前插入对象在数据库中的id写回到该实体中
        System.out.println(employee.getId());
    }
}

To perform the adding operation, just call the insert method to pass in the entity.

2. Update operation:

@Test
public void testUpdate(){
        Employee employee = new Employee();
        employee.setId(1);
        employee.setLastName("更新测试");
        //emplopyeeDao.updateById(employee);//根据id进行更新,没有传值的属性就不会更新
        emplopyeeDao.updateAllColumnById(employee);//根据id进行更新,没传值的属性就更新为null
}

Note: Pay attention to the difference between these two update operations, updateByIdmethods, fields without value passing will not be updated, for example, if only lastName is passed in, then attributes such as age and gender will retain their original values; methods, as the name implies, updateAllColumnByIdwill update all Columns with no values ​​will be updated to null.

3. select operation:

(1) Query according to id:

Employee employee = emplopyeeDao.selectById(1);

(2) Query a piece of data according to the condition:

Employee employeeCondition = new Employee();
employeeCondition.setId(1);
employeeCondition.setLastName("更新测试");
//若是数据库中符合传入的条件的记录有多条,那就不能用这个方法,会报错
Employee employee = emplopyeeDao.selectOne(employeeCondition);

Note: The sql statement of this method is where id = 1 and last_name = 更新测试that if there is more than one record that meets this condition, an error will be reported.

(3) Return multiple pieces of data according to the query conditions:
When there are multiple records that meet the specified conditions, the above method will report an error, so this method should be used.

Map<String,Object> columnMap = new HashMap<>();
columnMap.put("last_name","东方不败");//写表中的列名
columnMap.put("gender","1");
List<Employee> employees = emplopyeeDao.selectByMap(columnMap);
System.out.println(employees.size());

Note: The query condition is encapsulated with the map collection, columnMap, writes the column name in the data table, not the attribute name of the entity class. For example, the attribute name is lastName, the field in the data table is last_name, and last_name should be written here. The return value of the selectByMap method is received by the list collection.

(4) Batch query by id:

List<Integer> idList = new ArrayList<>();
idList.add(1);
idList.add(2);
idList.add(3);
List<Employee> employees = emplopyeeDao.selectBatchIds(idList);
System.out.println(employees);

Note: Add all the ids that need to be queried to the list collection, then call the selectBatchIds method and pass in the list collection. This method returns all records corresponding to the id, and all return values ​​are also received by the list.

(5), paging query:

List<Employee> employees = emplopyeeDao.selectPage(new Page<>(1,2),null);
System.out.println(employees);

Note: The selectPage method is a paging query. The paging information is passed in the page. The latter is a null paging condition. Let it be null first, and then talk about its usage after talking about the condition constructor. This paging is not actually a physical paging, but a memory paging. In other words, there is no limit statement when querying. The real paging can only be realized after the paging plug-in is configured.

4. Delete operation:

(1), delete according to id:

emplopyeeDao.deleteById(1);

(2), delete according to the conditions:

Map<String,Object> columnMap = new HashMap<>();
columnMap.put("gender",0);
columnMap.put("age",18);
emplopyeeDao.deleteByMap(columnMap);

Note: This method is similar to selectByMap. Encapsulate the condition in columnMap, then call the deleteByMap method and pass in columnMap. The return value is of type Integer, indicating the number of affected rows.

(3), delete in batches according to id:

 List<Integer> idList = new ArrayList<>();
 idList.add(1);
 idList.add(2);
 emplopyeeDao.deleteBatchIds(idList);

Note: This method is similar to selectBatchIds, put the id of the record to be deleted into idList, then call deleteBatchIds, and pass in idList.

4. Global policy configuration:

Through the above small case, we can find that the entity class needs to add the @TableName annotation to specify the database table name, and specify the id growth strategy through the @TableId annotation. It doesn't matter if there are few entity classes, but it will be troublesome if there are too many entity classes. Therefore, global policy configuration can be performed in the spring-dao.xml file.

<!-- 5、mybatisplus的全局策略配置 -->
<bean id="globalConfiguration" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
        <!-- 2.3版本后,驼峰命名默认值就是true,所以可不配置 -->
        <!--<property name="dbColumnUnderline" value="true"/>-->
        <!-- 全局主键自增策略,0表示auto -->
        <property name="idType" value="0"/>
        <!-- 全局表前缀配置 -->
        <property name="tablePrefix" value="tb_"/>
</bean>

The configuration here is not used yet, and the configuration needs to be injected into sqlSessionFactory to take effect. as follows:

<!-- 3、配置mybatisplus的sqlSessionFactory -->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="typeAliasesPackage" value="com.zhu.mybatisplus.entity"/>
        <!-- 注入全局配置 -->
        <property name="globalConfig" ref="globalConfiguration"/>
</bean>

In this way, the @TableName annotation and @TableId annotation in the entity class can be removed.
 

5. Conditional constructor (EntityWrapper):

For the above basic CRUD operations, we only need to inherit a BaseMapper to implement most of the single-table CRUD operations. BaseMapper provides as many as 17 methods for use, which can realize single, batch, paging and other operations extremely conveniently, greatly reducing the development burden. But the power of mybatis-plus is not limited to this. Please see how to deal with the following requirements:
Requirements:
We need to query all users in the tb_employee table who are between 18 and 50 and whose gender is male and whose name is xx. At this time, we should How to achieve the above requirements?
Using MyBatis: You need to write SQL with conditional query in the SQL mapping file, and use the PageHelper plug-in to complete the paging. To achieve the above simple requirement, we often need to do a lot of repetitive and monotonous work.
Using MP: still do not need to write SQL statements, MP provides a powerful conditional constructor ------ EntityWrapper.

Next, let's directly look at a few cases to experience the use of EntityWrapper.

1. Page query for users whose age is 18-50, gender is 0, and their name is tom:

List<Employee> employees = emplopyeeDao.selectPage(new Page<Employee>(1,3),
     new EntityWrapper<Employee>()
        .between("age",18,50)
        .eq("gender",0)
        .eq("last_name","tom")
);

Note: From this case, we can see that the paging query is the same as before, and a new page object can be passed in the paging information. As for the paging condition, just create a new EntityWrapper object and call the related methods of the object. The three parameters of the between method are column, value1, and value2. This method indicates that the value of the column should be between value1 and value2; eq is shorthand for equals. The two parameters of this method, column and value, indicate the value and value of the column To be equal. Note that column is the field corresponding to the data table, not the attribute field of the entity class.

2. Query the users with a gender of 0 and a teacher in their name, or a in their mailbox:

List<Employee> employees = emplopyeeDao.selectList(
                new EntityWrapper<Employee>()
               .eq("gender",0)
               .like("last_name","老师")
                //.or()//和or new 区别不大
               .orNew()
               .like("email","a")
);

Note: Paging query is not mentioned, so you can use selectList, and use the like method of EntityWrapper to perform fuzzy query. The like method means that the value of the column contains the value value. Here, the like method is to query the records containing the word "teacher" in the last_name;" Or" is represented by the or or orNew method. The difference between these two methods is not great, and you can use either one. You can feel the difference by yourself through the sql statement on the console.

3. The query gender is 0, sorted according to age, and simple pagination:

List<Employee> employees = emplopyeeDao.selectList(
                new EntityWrapper<Employee>()
                .eq("gender",0)
                .orderBy("age")//直接orderby 是升序,asc
                .last("desc limit 1,3")//在sql语句后面追加last里面的内容(改为降序,同时分页)
);

Note: Simple paging refers to paging without page objects. The orderBy method is to sort in ascending order according to the incoming column. If you want to order in descending order, you can use the orderByDesc method, or you can use the last method as shown in the case; the last method is to append the value in the last method to the end of the SQL statement. In this case, the last sql statement becomes select ······ order by desc limit 1, 3, appended desc limit 1,3so that descending sorting and pagination can be performed.

4. Page query for users whose age is 18-50, whose gender is 0, and whose name is tom: the
condition constructor not only has EntityWrapper, but also Condition. Use Condition to handle this requirement:

 List<Employee> employees = emplopyeeDao.selectPage(
                new Page<Employee>(1,2),
                Condition.create()
                        .between("age",18,50)
                        .eq("gender","0")
 );

Note: The difference between Condition and EntityWrapper is that when creating a conditional constructor, EntityWrapper is new, while Condition is created by calling the create method.

5. Update according to the conditions:

@Test
public void testEntityWrapperUpdate(){
        Employee employee = new Employee();
        employee.setLastName("苍老师");
        employee.setEmail("[email protected]");
        employee.setGender(0);
        emplopyeeDao.update(employee,
                new EntityWrapper<Employee>()
                .eq("last_name","tom")
                .eq("age",25)
        );
}

Note: This example indicates that the information of all users whose last_name is tom and age is 25 is updated to the information set in employee.

6. Delete according to the conditions:

emplopyeeDao.delete(
        new EntityWrapper<Employee>()
        .eq("last_name","tom")
        .eq("age",16)
);

Note: In this case, all users whose last_name is tom and age is 16 are deleted.

#@your#

帮助到您请点赞关注收藏谢谢!!

Guess you like

Origin blog.csdn.net/qq_18432653/article/details/116455987