The operation of the database is an indispensable function in our company. Mybatis Plus is an enhancement based on Mybatis, which makes it more convenient for us to use some basic CRUD. This article mainly talks about how SpringBoot integrates Mybatis Plus. , and implement basic CRUD functions.
1. Introduce the corresponding dependencies
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
复制代码
Imported mybatis-plus
dependencies and mysql
driven dependencies.
2. Configure
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb?characterEncoding=utf-8&serverTimeZone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: auto
logic-delete-field: deleted
logic-delete-value: 1
logic-not-delete-value: 0
复制代码
spring.datasource
It is the configuration of the link information of the database
mybatis-plus
:
configuration.log-impl
: configure to print sql logid-type
: id primary key generation strategy, auto means self-incrementlogic-delete-field
: Logical delete field, online databases generally need to configure logical deletionlogic-delete-value
: tombstone deleted valueslogic-not-delete-value
: Tombstone undeleted values
3. Create a new database table
Here I create a simpleuser表
The sql is as follows:
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`age` int(3) NOT NULL,
`create_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`deleted` int(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
复制代码
You can see that there are some necessary fields in the table create_time
, update_time
, deleted
, and we need to configure the first two fields in the project Mybatis Plus
to let him automatically insert values when we add data and update data, and deleted
logically delete fields because we are already in yml After configuration, we don't need to deal with it later.
Fourth, configure Mybatis Plus to automatically fill
Configure Mybatis Plus
autofill to automatically insert and update values create_time
for .update_time
- new
handler.mybatisplus.MyMetaObjectHandler
class - This class implements
MetaObjectHandler
the interface - and override the
insertFille
andupdateFill
method
The specific code is implemented as follows:
handler.mybatisplus.MyMetaObjectHandler:
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import java.util.Date;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
setFieldValByName("createTime", new Date(), metaObject);
setFieldValByName("updateTime", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
setFieldValByName("updateTime", new Date(), metaObject);
}
}
复制代码
Five, implement the User entity class, UserMapper, UserService
- User entity class
domain.entity.User:
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@TableName("user")
public class User {
@TableId
private Long id;
private String username;
private Integer age;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
private Integer deleted;
}
复制代码
@TableName
: Specify the table name corresponding to the entity class
@TableId
: Specify the primary key, what we configure is auto
the primary key auto-increment strategy
@TableField
: Specifies that the value uses our autofill strategy, INSERT
fill-on-insert, INSERT_UPDATE
fill-on-insert and update-time
- UserMapper
mapper.UserMapper
:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jk.domain.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
复制代码
Mybatis Plus
Provided by inheritance BaseMapper
, some basic CRUD interfaces have been implemented
- UserService
service.UserService
:
public interface UserService {
}
复制代码
service.impl.UserServiceImpl
:
import com.jk.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
}
复制代码
service
First build the corresponding ones , controller
and implement them together later.
6. Use Restful style to realize CRUD function
- Preparation
Because we need to use the paging function when looking up the list, we need to configure Mybatis Plus
the paging plug-in
config.MybatisPlus
:
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlus {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
}
复制代码
In addition, because we do not need all the entity fields when adding and updating, we need to create the corresponding DTO to receive the front-end data, and we do not need all the fields when returning. We need the corresponding Vo pairs to return the fields required by the front-end
domain.dto.AddUserDto
:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AddUserDto {
private String username;
private Integer age;
}
复制代码
domain.dto.UpdateUserDto
:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UpdateUserDto {
private Long id;
private String username;
private Integer age;
}
复制代码
domain.vo.UserVo
:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserVo {
private Long id;
private String username;
private Integer age;
private Date createTime;
}
复制代码
domain.vo.PageVo
:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageVo {
private List result;
private Long total;
}
复制代码
PageVo
Used to handle all responses that require paged data
Regarding the unified response, you can see the unified response format and unified exception handling in SpringBoot, you should do this
Regarding Bean copying, you can see Bean copying and tool class encapsulation in the SpringBoot project
CRUD
correspondingcontroller
controller.UserController
:
import com.jk.domain.dto.AddUserDto;
import com.jk.domain.dto.UpdateUserDto;
import com.jk.service.UserService;
import com.jk.domain.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public ResponseResult addUser(@RequestBody AddUserDto addUserDto) {
return userService.addUser(addUserDto);
}
@PutMapping
public ResponseResult updateUser(@RequestBody UpdateUserDto updateUserDto) {
return userService.updateUser(updateUserDto);
}
@DeleteMapping("/{id}")
public ResponseResult deleteUser(@PathVariable("id") Long id) {
return userService.deleteUser(id);
}
@GetMapping
public ResponseResult getUser(@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize) {
return userService.getUser(pageNum, pageSize);
}
}
复制代码
CRUD
correspondingservice
service.UserService
:
import com.jk.domain.dto.AddUserDto;
import com.jk.domain.dto.UpdateUserDto;
import com.jk.domain.vo.ResponseResult;
public interface UserService {
ResponseResult addUser(AddUserDto addUserDto);
ResponseResult updateUser(UpdateUserDto updateUserDto);
ResponseResult deleteUser(Long id);
ResponseResult getUser(Integer pageNum, Integer pageSize);
}
复制代码
CRUD
shouldservice实现类
service.impl.UserServiceImpl
:
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jk.domain.dto.AddUserDto;
import com.jk.domain.dto.UpdateUserDto;
import com.jk.domain.entity.User;
import com.jk.domain.vo.UserVo;
import com.jk.mapper.UserMapper;
import com.jk.service.UserService;
import com.jk.domain.vo.PageVo;
import com.jk.domain.vo.ResponseResult;
import com.jk.utils.BeanCopyUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public ResponseResult addUser(AddUserDto addUserDto) {
User user = BeanCopyUtils.copyBean(addUserDto, User.class);
userMapper.insert(user);
return ResponseResult.okResult();
}
@Override
public ResponseResult updateUser(UpdateUserDto updateUserDto) {
User user = new User();
BeanUtils.copyProperties(updateUserDto, user);
userMapper.updateById(user);
return ResponseResult.okResult();
}
@Override
public ResponseResult deleteUser(Long id) {
userMapper.deleteById(id);
return ResponseResult.okResult();
}
@Override
public ResponseResult getUser(Integer pageNum, Integer pageSize) {
Page<User> userPage = new Page<>(pageNum, pageSize);
userMapper.selectPage(userPage, null);
List<UserVo> userVos = BeanCopyUtils.copyBeanList(userPage.getRecords(), UserVo.class);
PageVo pageVo = new PageVo(userVos, userPage.getTotal());
return ResponseResult.okResult(pageVo);
}
}
复制代码
About SpringBoot Integrate Mybatis Plus to achieve basic CRUD functions This is the case, among which we have expanded many functions, which are necessary for enterprise development