preface
There are many Java persistence frameworks, such as Hibernate, Mybatis, Spring Data JPA, etc., and now the mainstream play is SSM, that is, Spring + SpringMVC + Mybatis. This rapid development framework selects the persistence framework for Mybatis, and the purpose of using Mapper is to achieve the general method of Mybatis, which can reduce the generation of a large number of XML files. Of course, there is also a framework similar to Mapper, such as Mybatis Plus, interested students can know.
start
Build table
CREATE TABLE `sys_user` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'primary key'.`user_name` varchar(32) NOT NULL COMMENT 'Username'.`real_name` varchar(32) DEFAULT NULL COMMENT 'name'.`avatar` varchar(200) DEFAULT NULL COMMENT 'avatar'.`email` varchar(64) DEFAULT NULL COMMENT 'email'.`mobile_phone` varchar(11) DEFAULT NULL COMMENT 'Mobile phone Number'.`telephone` varchar(20) DEFAULT NULL COMMENT 'phone'.`password` varchar(40) DEFAULT NULL COMMENT 'password'.`salt` varchar(10) DEFAULT NULL COMMENT 'salt'.`sex` int(6) unsigned DEFAULT '0' COMMENT 'gender (0 - > | UNKNOWN UNKNOWN, 1 - > MALE | MALE, FEMALE 2 - > | FEMALE)'.`is_locked` tinyint(1) unsigned DEFAULT '0' COMMENT 'whether lock (1 - > | YES, 0 - > NO | NO)'.`create_time` datetime DEFAULT NULL COMMENT 'Creation time'.`update_time` datetime DEFAULT NULL COMMENT 'Update Time'.`is_deleted` tinyint(1) unsigned DEFAULT '0' COMMENT 'whether delete (1 - > delete | YES, 0 - > not delete | NO)',
PRIMARY KEY (`id`))ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='users';
Copy the code
The directory structure
List only files that need to be added or modified
├─ ├─ SRC /main/ Java ├─ Java ├─ SRC /main/ Java ├─ SRC /main/ Java ├─ Java ├─ SRC /main/ Java ├─ Java ├─ SRC /main/ Java ├─ Java ├─ SRC /main/ Java ├─ Java ├─ SRC /main/ Java ├─ Java ├─ SRC /main/ Java ├─ Java ├─ Service service layer ├ ─ ─ impl └ ─ ─ SysUserServiceImpl └ ─ ─ SysUserService. Java └ ─ ─ SRC/main/resources ├ ─ ─ application - dev. Yml └ ─ ─ ├─ ├─ general exercises, ├─ general exercises, ├─ general Exercises, com.mldong.modules ├─ ├─ imp (1), ├─ imp (2), imp (2), imp (2), imp (3), imp (3), imp (3), imp (4), imp (4), imp (4), imp (4), imp (5), imp (5), imp (5Copy the code
Document describing
- Mldong-mapper /pom.xml added dependencies
<! -- tk.mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.spring.boot.starter.version}</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>${tk.mybatis.version}</version>
</dependency>
<! --mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>${mapper.spring.boot.starter.version}</version>
</dependency>
<! --pagehelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pagehelper.spring.boot.starter.version}</version>
</dependency>
<! -- tk.mybatis -->
Copy the code
The parent project already has a version number, but a copy is kept here for easy copying
<properties>
<tk.mybatis.version>4.1.5</tk.mybatis.version>
<mybatis.spring.boot.starter.version>2.1.0</mybatis.spring.boot.starter.version>
<mapper.spring.boot.starter.version>2.1.0</mapper.spring.boot.starter.version>
<pagehelper.spring.boot.starter.version>1.2.12</pagehelper.spring.boot.starter.version>
</properties>
Copy the code
- Mldong – admin/SRC/main/resources/application. The new mybatis mapper, yml pagehelper configuration
server:
port: 18080
spring:
application:
name: mldong-admin
profiles:
active: dev
jackson:
default-property-inclusion: non_null
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: ${jdbc.driver-class-name}
url: ${jdbc.url}
username: ${jdbc.username}
password: ${jdbc.password}
max-idle: ${jdbc.max-idle}
max-wait: ${jdbc.max-wait}
min-idle: ${jdbc.min-idle}
aop:
proxy-target-class: true
auto: true
# mybatis configuration
mybatis:
type-aliases-package: com.mldong.modules.*.mapper.*,com.mldong.modules.*.dao.*,com.mldong.modules.*.repo.*
mapper-locations: classpath*:mapper/*/*.xml,classpath*:dao/*/*.xml,classpath*:repo/*/*.xml
configuration:
map-underscore-to-camel-case: true
# mapper configuration
mapper:
mappers:
- tk.mybatis.mapper.common.BaseMapper
not-empty: false
identity: MYSQL
use-simple-type: true
enum-as-simple-type: true
# Paging plug-in configuration
pagehelper:
helperDialect: mysql
reasonable: false
supportMethodsArguments: true
params: count=countSql
Copy the code
- To log the input SQL statements mldong – admin/SRC/main/resources/application – dev. Yml modified as follows
# log configuration
logging:
level:
com.mldong: DEBUG
org.springframework: DEBUG
tk.mybatis: DEBUG
tk.ibatis: DEBUG
tk.ibatis.common.jdbc.SimpleDataSource: DEBUG
tk.ibatis.common.jdbc.ScriptRunner: DEBUG
tk.ibatis.sqlmap.engine.impl.SqlMapClientDelegate: DEBUG
java.sql.Connection: DEBUG
java.sql.Statement: DEBUG
java.sql.PreparedStatement: DEBUG
org.springframework.scheduling: INFO
# JDBC configuration
jdbc.driver-class-name: com.mysql.cj.jdbc.Driver
jdbc.url: jdbc:mysql://localhost:3306/mldong? useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai
jdbc.username: root
jdbc.password:
jdbc.max-idle: 10
jdbc.max-wait: 10000
jdbc.min-idle: 5
Copy the code
- Mldong – admin/SRC/main/Java/com/mldong MldongAdminApplication. New mapper Java annotation scanning
package com.mldong;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan(basePackages = {"com.mldong.modules.*.mapper"."com.mldong.modules.*.dao"."com.mldong.modules.*.repo"})
@EnableTransactionManagement
public class MldongAdminApplication {
public static void main(String[] args) { SpringApplication.run(MldongAdminApplication.class, args); }}Copy the code
- New file mldong mapper/SRC/main/Java/com/mldong/modules/sys/entity/SysUser. Java
package com.mldong.modules.sys.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Table;
/** * user table *@author MLD
*
*/
@Table(name="sys_user")
public class SysUser implements Serializable{
/ * * * * /
private static final long serialVersionUID = -2687095050668229447L;
private Long id;
private String userName;
private String realName;
private String avatar;
private String email;
private String mobilePhone;
private String telephone;
private String password;
private String salt;
private Integer sex;
private Boolean isLocked;
private Date createTime;
private Date updateTime;
private Boolean isDeleted;
/ / get the set slightly
}
Copy the code
- New file mldong mapper/SRC/main/Java/com/mldong/modules/sys/mapper/SysUserMapper. Java
package com.mldong.modules.sys.mapper;
import com.mldong.modules.sys.entity.SysUser;
import tk.mybatis.mapper.common.BaseMapper;
/** * sys_user persistence layer *@author MLD
*
*/
public interface SysUserMapper extends BaseMapper<SysUser>{}Copy the code
- New file mldong – admin/SRC/main/Java/com/mldong/modules/sys/service/SysUserService Java
package com.mldong.modules.sys.service;
import com.github.pagehelper.Page;
import com.mldong.modules.sys.entity.SysUser;
public interface SysUserService {
/** * Add user *@param param
* @return* /
public int save(SysUser param);
/** * Update user *@param param
* @return* /
public int update(SysUser param);
/** * Delete user *@param id
* @return* /
public int delete(Long id);
/** * Query user *@param id
* @return* /
public SysUser get(Long id);
/** ** page query user list *@param t
* @param pageNum
* @param pageSize
* @return* /
public Page<SysUser> list(SysUser t, int pageNum, int pageSize);
}
Copy the code
- New file mldong – admin/SRC/main/Java/com/mldong/modules/sys/service/impl SysUserServiceImpl. Java
package com.mldong.modules.sys.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mldong.modules.sys.entity.SysUser;
import com.mldong.modules.sys.mapper.SysUserMapper;
import com.mldong.modules.sys.service.SysUserService;
@Service
public class SysUserServiceImpl implements SysUserService{
@Autowired
private SysUserMapper sysUserMapper;
@Override
public int save(SysUser param) {
return sysUserMapper.insertSelective(param);
}
@Override
public int update(SysUser param) {
return sysUserMapper.updateByPrimaryKeySelective(param);
}
@Override
public int delete(Long id) {
return sysUserMapper.deleteByPrimaryKey(id);
}
@Override
public SysUser get(Long id) {
return sysUserMapper.selectByPrimaryKey(id);
}
@Override
public Page<SysUser> list(SysUser t, int pageNum, int pageSize) {
Page<SysUser> page = PageHelper.startPage(pageNum, pageSize,true);
sysUserMapper.select(t);
returnpage; }}Copy the code
- New file mldong – admin/SRC/main/Java/com/mldong/modules/sys/controller/SysUserController. Java
package com.mldong.modules.sys.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.Page;
import com.mldong.modules.sys.entity.SysUser;
import com.mldong.modules.sys.service.SysUserService;
@RestController
@RequestMapping("/sys/user")
public class SysUserController {
@Autowired
private SysUserService sysUserService;
/** * Add user *@param param
* @return* /
@PostMapping("save")
public int save(@RequestBody SysUser param) {
return sysUserService.save(param);
}
/** * Update user *@param param
* @return* /
@PostMapping("update")
public int update(@RequestBody SysUser param) {
return sysUserService.update(param);
}
/** * Delete user *@param param
* @return* /
@PostMapping("delete")
public int delete(Long id) {
return sysUserService.delete(id);
}
/** * Get user * by id@param param
* @return* /
@GetMapping("get")
public SysUser get(Long id) {
return sysUserService.get(id);
}
/** ** page query user list *@param param
* @return* /
@GetMapping("list")
public Page<SysUser> list(SysUser param, @RequestParam(defaultValue="1")Integer pageNum, @RequestParam(defaultValue="10")int pageSize) {
returnsysUserService.list(param, pageNum, pageSize); }}Copy the code
Start running the project
MldongAdminApplication.java
Right-click ->Run As -> Java Application
To access the page
http://localhost:18080/sys/user/list
If the project starts normally, the access page will have user list data. You can use Postman to test other interfaces. At this point, mapper integration is complete, and the next article will integrate Swaggerui and Knife4J.
This section describes common mapper methods
methods | instructions |
---|---|
List select(T record); | Query according to the attribute value in the entity, query condition using equal sign |
T selectByPrimaryKey(Object key); | To query based on the primary key field, the method parameter must contain the complete primary key attribute, and the query condition uses an equal sign |
List selectAll(); | The select(NULL) method does the same thing |
T selectOne(T record); | According to the attributes in the entity to query, can only have a return value, there are more than one result is thrown exceptions, query conditions using equal sign |
int selectCount(T record); | Based on the total number of attributes in the entity, the query condition uses an equal sign |
int insert(T record); | When an entity is saved, the null attribute is also saved. The database default is not used |
int insertSelective(T record); | To save an entity, the null attribute is not saved, and the database default value is used |
int updateByPrimaryKey(T record); | Update all fields of the entity based on the primary key, null values will be updated |
int updateByPrimaryKeySelective(T record); | Update values whose attributes are not NULL based on the primary key |
int delete(T record); | Delete according to entity attribute as condition, query condition using equal sign |
int deleteByPrimaryKey(Object key); | To delete by primary key field, the method parameter must contain the full primary key attribute |
List selectByExample(Object example); | Query based on the Example condition, which supports specifying query columns through the Example class and the selectProperties method |
int selectCountByExample(Object example); | Query the total number based on the Example condition |
int updateByExample(@Param(“record”) T record, @Param(“example”) Object example); | Update all attributes contained in the entity Record according to the Example condition, and null values are updated |
int updateByExampleSelective(@Param(“record”) T record, @Param(“example”) Object example); | Update the entity Record containing property values that are not null based on the Example condition |
int deleteByExample(Object example); | Delete data according to the Example condition |
Project source code address
- The back-end
Gitee.com/mldong/mldo…
- The front end
Gitee.com/mldong/mldo…
Related articles
Create a suitable for their own rapid development framework – the pilot
Build a suitable for their own rapid development framework – back-end scaffolding