1. Introduction
With many advantages like light-weighted structures and easy-to-use methods, Mybatis has became a popular Java repository layer framework, especially in China. However, since Mybatis needs programmers to create every SQL for querying, it is quite complicated and inflexible toward simple queries or single table queries. Therefore, the Mybatis team combined good characteristics from other frameworks like Hibernate and published a brand new repository layer framework called Mybatis-plus in 2019.
This tutorial aims at introducing some essential points of Mybatis-plus.
2. Environment Set Up and Dependencies
The first step of implementing Mybatis-plus is setting up the proper environment and dependencies. The Mybatis-plus-boot is used in the Pom file. One important thing is that we should only add the Mybatis-plus dependency while avoiding the Mybatis dependency. These two dependencies may confuse IDEA.
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
Then in the Yml or properties file, we need to add regular JDBC settings.
spring.datasource.url=jdbc:mysql://localhost:3306/example?characterEncoding=utf8
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.tomcat.max-active=100
spring.datasource.tomcat.min-idle=20
spring.datasource.tomcat.max-wait=5000
spring.main.allow-circular-references=true
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
Finally, similar to the Mybatis, we must add "@MapperScan" in our MainServer class.
@SpringBootApplication
@MapperScan("com.tencent.mybatisp.MpDemo")
public class MpDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MpDemoApplication.class, args);
}
}
3. Map Entity Class
After properly setting up our environment, the next step is to map our table with entity classes. This process is pretty similar to the JPA mapping (more than 80% similarity).
@TableName("user")
//"TableName" This is the table name in database
@AllArgsConstructor
@NoArgsConstructor
public class UserBean {
@TableId(value = "pk_id", type = IdType.AUTO)
//The @TableId indicates the primary key of the table you use.
//The IdType.AUTO is similar to "GeneratedValue" in JPA
private Integer id;
@TableField("f_name")
private String name;
//@TableField's value is the table column name in database table
@TableField("f_birth")
private LocalDate birth;
@TableField("f_gender")
private String gender;
@TableField("f_password")
private String password;
@TableField("f_role")
private String role;
public UserBean(String name, LocalDate birth, String gender, String password, String role) {
this.name = name;
this.birth = birth;
this.gender = gender;
this.password = password;
this.role = role;
}
//...getter and setter method are created
}
Code above is the example of a user entity's mapping in the Mybatis-plus. It is obvious to see that the process is very similar to JPA's. After properly defined the mapping entity class, it is now time to add our DAO (AKA mapper) class.
public interface IUserDao extends BaseMapper<UserBean> {
}
Compares to mapper classes in the Mybatis, DAO classes in the Mybatis-plus is much simpler. We don't even have to write any SQL query but extends the BaseMapper class. That's all! We can then directly use it to do simple CRUD.
4. Basic CRUD Instance
Finally, let's test our Mybatis-plus application in test class. In Mybatis-plus, there is a crucial component called "Wrapper" class. In a nutshell, the wrapper class is created to indicate the query terms we want to specify. Here is some example of the wrapper classes:
@Test
void deleteUser(){
QueryWrapper<UserBean> wrapper = new QueryWrapper<>();
wrapper.eq("f_name","刘宏");//This means rows whose "f_name" is "刘宏"
wrapper.like("f_name","刘");//This means rows whose "f_name" contains "刘宏"
userDao.selectList(wrapper);//select all that satisfy one of the two requirements above
}
With wrapper class, it is very simple to practice basic CRUD procedures.
@Test
void CrudMethodDemo() {
//Insert new user, we need to apply "insert" method.
userDao.insert(new UserBean("刘婵",LocalDate.now(),"男","abc123","会员"));
userDao.insert(new UserBean("刘宏",LocalDate.now(),"男","abc123","游客"));
userDao.insert(new UserBean("貂蝉",LocalDate.now(),"女","ab4323","会员"));
//delete users in two ways
QueryWrapper<UserBean> delWrapper = new QueryWrapper<>();
delWrapper.eq("f_name","刘宏");
userDao.delete(delWrapper);
//or
userDao.deleteById(2);//This id is the primary key that annotated with "@TableId"
//select method
QueryWrapper<UserBean> wrapper = new QueryWrapper<>();
wrapper.eq("f_name","刘宏");//This means rows whose "f_name" is "刘宏"
wrapper.like("f_name","刘");//This means rows whose "f_name" contains "刘宏"
userDao.selectList(wrapper);//select all that satisfy one of the two requirements above
//Last is the update
userDao.update(new UserBean("刘婵",LocalDate.now(),"男","abc123","会员"),wrapper);
}
5. Conclusion
Mybatis-plus is a upgraded version of the Mybatis. It does not change any feature of the original Mybatis framework but adds new features to it. Mybatis-plus is very handy in dealing with simple CRUD procedure, especially towards single table. However, if we need to do cross table querying, it is recommended to use the original Mybatis. For more information about mybatis-plus like pagination, you can check out in Mybatis-plus's offical website.