What are the characteristics of MyBatis-plus
1. Code generation 2. Conditional constructor
For me, the main purpose is to use its powerful conditional builder.
Quick steps to use:
1. Add pom file dependencies
<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version></dependency><dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.0.1</version> </dependency>
Note: mybatis-plus will automatically maintain the dependencies of mybatis and mybatis-spring, so there is no need to introduce the latter two to avoid version conflicts.
2. Modify the configuration file
Just replace mybatis' sqlSessionFactory with mybatis-plus. Mybatis-plus only does some functional extensions:
<bean id="sqlSessionFactory"> <property name="dataSource" ref="dataSource"/> <!-- Automatic scan of Mapping.xml file --> <property name="mapperLocations" value="classpath:mybatis/*/*.xml"/> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> <property name="typeAliasesPackage" value="com.baomidou.springmvc.model.*"/> <property name="plugins"> <array> <!-- Pagination Plugin Configuration--> <bean id="paginationInterceptor"> <property name="dialectType" value="mysql"/> </bean> </array> </property> <!-- Global Configuration Injection--> <property name="globalConfig" ref="globalConfig" /> </bean>
In the above configuration, in addition to the regular configuration of mybatis, there is an additional configuration and global configuration of pagination plug-in. Mybatis-plus provides a very convenient use of pagination plug-in, and there is also a global configuration as follows:
<bean id="globalConfig"> <!-- AUTO->0`("Database ID self-increment") INPUT->`1`(User input ID") ID_WORKER->`2`("Global unique ID") UUID->`3`("Global unique ID") --> <property name="idType" value="2" /> <!-- MYSQL->`mysql` ORACLE->`oracle` DB2->`db2` H2->`h2` HSQL->`hsql` SQLITE->`sqlite` POSTGRE->`postgresql` SQLSERVER2005->`sqlserver2005` SQLSERVER->`sqlserver` --> <!-- Oracle needs to add this item --> <!-- <property name="dbType" value="oracle" /> --> <!-- Global table sets true for underscore name --> <property name="dbColumnUnderline" value="true" /> </bean>At this point, even if the configuration work is completed, let’s use a simple example to experience its use.
1. Create a new User table:
@TableName("user")public class User implements Serializable { /** User ID */ private Long id; /** User name */ private String name; /** User age */ private Integer age; @TableField(exist = false) private String state;}There are two annotations to note here. The first is @tableName("user"), which specifies the association with the database table. The annotation here means that there should be a table named user in your database corresponding to it, and the column name of the data table should be the attributes of the User class. For attributes that are in the User class but do not have in the user table, a second annotation @TableField(exist = false) is required to exclude attributes in the User class.
2. Create a new Dao layer interface UserMapper:
/** * User table database control layer interface*/public interface UserMapper extends BaseMapper<User> { @Select("selectUserList") List<User> selectUserList(Pagination page,String state);}The dao interface needs to implement Basemapper, so that many encapsulated methods can be used. In addition, you can also write methods yourself. @select annotation refers to the UserMapper file referenced from the third step.
3. Create a new UserMapper configuration file:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.baomidou.springmvc.mapper.system.UserMapper"> <!-- General Query Results Column--> <sql id="Base_Column_List"> id, name, age </sql> <select id="selectUserList" resultType="User"> SELECT * FROM sys_user WHERE state=#{state} </select></mapper>4. Create a new service layer class UserService:
/** * * User table data service layer interface implementation class* */@Servicepublic class UserService extends ServiceImpl<UserMapper, User>{ public Page<User> selectUserPage(Page<User> page, String state) { page.setRecords(baseMapper.selectUserList(page,state)); return page; }}UserService inherits the ServiceImpl class. Mybatis-plus injects UserMapper into us in this way. This way, we can use many methods provided by the service layer by default, and we can also call the methods we write in the dao layer to operate the database. The Page class is a model that mybatis-plus provides pagination function, inherits Pagination, so we don't need to write another Page class ourselves, just use it directly.
5. Create a new controller layer UserController
@Controllerpublic class UserController extends BaseController { @Autowired private IUserService userService; @ResponseBody @RequestMapping("/page") public Object selectPage(Model model){ Page page=new Page(1,10); page = userService.selectUserPage(page, "NORMAL"); return page; }The above completes a basic function. Let’s take a look at its conditional builder.
Conditional builder for mybatis-plus
First, let’s look at the simple and practicality of a conditional builder instance.
public void test(){ EntityWrapper ew=new EntityWrapper(); ew.setEntity(new User()); String name="wang"; Integer age=16; ew.where("name = {0}",name).andNew("age > {0}",age).orderBy("age"); List<User> list = userService.selectList(ew); Page page2 = userService.selectPage(page, ew); }Here, a conditional wrapper class EntityWrapper is used to assemble SQL statements. The principle is also easy to understand. In the above code, the result of the first list query is to query all records in the database with name=wang and age>16 years old and sort them according to age. The second query is to add another pagination function.
Basically, using EntityWrapper can simply complete some conditional queries, but if the query method is used very frequently, it is recommended to write it in UserMapper yourself.
So can the custom mapper method use EntityWrapper? Of course, it is also possible.
An example of this is given in the documentation.
1. Definition in Mappper:
List<User> selectMyPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper);
2. Define in the mapper file:
<select id="selectMyPage" resultType="User"> SELECT * FROM user ${ew.sqlSegment}</select>For the conditional splicing of EntityMapper, we can basically implement where, and, or, groupby, orderby and other syntax commonly used in SQL, and the specific construction methods can be flexibly combined.
@Testpublic void testTSQL11() { /* * Entity with query usage method output to see the result */ ew.setEntity(new User(1)); ew.where("name={0}", "'zhangsan'").and("id=1") .orNew("status={0}", "0").or("status=1") .notLike("nlike", "notvalue") .andNew("new=xx").like("hhh", "ddd") .andNew("pwd=11").isNotNull("n1,n2").isNull("n3") .groupBy("x1").groupBy("x2,x3") .having("x1=11").having("x3=433") .orderBy("dd").orderBy("d1,d2"); System.out.println(ew.getSqlSegment());}Reference Documents
mybaits-plus official documentation
Summarize
The above is the quick introduction tutorial for the MyBatis Plus tool introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time!