• The universal Mapper simplifies CRUD operations on a single table
  • The PageHelper paging plug-in helps you automatically concatenate paging SQL

1. Introduce dependencies

<! -- mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 2.1.3 < / version > < / dependency > <! Mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> < version > 1. < / version > < / dependency > <! --> <dependency> <groupId>com.github. Pagehelper </groupId> < artifactId > pagehelper - spring - the boot - starter < / artifactId > < version > 1.2.10 < / version > < / dependency > <! Mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> The < version > 5.1.34 < / version > < / dependency >Copy the code

2. Configuration file

2.1 the pom. XML

Pay attention to the version, too high may be error, do not change the version

<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> The < version > 1.3.2 < / version > < dependencies > <! <dependency> <groupId>org.mybatis. Generator </groupId> < artifactId > mybatis generator - core < / artifactId > < version > 1.3.2 < / version > < / dependency > <! Mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>1.2.4</version> </dependency> </dependencies> <configuration> <! -- Allow moving generated files --> <verbose>true</verbose> <! -- overwrite --> <overwrite>true</overwrite> <! - automatically generate configuration - > < configurationFile > SRC/main/resources/mybatis - generator. XML < / configurationFile > < / configuration > </plugin>Copy the code
2.2 application. Yml
Mybatis mybatis: # type-aliases: type-aliases-package: com.springboot.bean # mapper XML: Classpath :mapper/*.xml property: order: BEFORE #mappers com.suruomo.springboot10mybatis.config.MyMapper not-empty: false identity: mysql #pagehelper pagehelper: helperDialect: Mysql Reason-valued: true supportMethodsArguments: true params: count=countSql # . Com. Mysql. JDBC Driver username: root password: suruomo url: JDBC: mysql: / / 127.0.0.1:3306 / demoCopy the code
2.3 mybatis generator. XML
<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration> <! Database driver: Select the database driver package on your local hard drive. Path should not appear in Chinese --> <classPathEntry Location = "D: \ Java \ MAVEN \ maven_repository/mysql/mysql - connector - Java \ 5.1.34 \ mysql connector - Java - 5.1.34. Jar" / > < context id="DB2Tables" targetRuntime="MyBatis3"> <plugin type="tk.mybatis.mapper.generator.MapperPlugin"> <! - the configuration can make the production of Mapper automatically inherit MyMapper - > < property name = "mappers" value = "com. Suruomo. Springboot10mybatis. Config. MyMapper" / > <! -- caseSensitive defaults to false, and can be set to true when database table names are caseSensitive --> <! -- <property name="caseSensitive" value="false"/>--> </plugin> <commentGenerator> <property name="javaFileEncoding" value="UTF-8"/> <property name="suppressDate" value="true"/> <! -- Whether to remove automatically generated comments true: yes: false: no --> < Property name="suppressAllComments" value="trur"/> </commentGenerator> <! Database link URL, User name and password - > < jdbcConnection driverClass = ". Com. Mysql. JDBC Driver "connectionURL =" JDBC: mysql: / / localhost: 3306 / demo? useUnicode=true" userId="root" password="suruomo"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <! - the package name and the position of the generated model - > < javaModelGenerator targetPackage = "com. Suruomo. Springboot10mybatis. Model" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <! <sqlMapGenerator targetPackage="mapper" targetProject=" SRC /main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <! - generate the DAO package name and location - > < javaClientGenerator type = "XMLMAPPER targetPackage" = "com. Suruomo. Springboot10mybatis. Mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <! --> <table tableName="user" --> enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="true"></table> </context> </generatorConfiguration>Copy the code

3. Automatically execute the generated code

Generate UserMapper + User + UserMapper. XML

Code 4.

4.1 Creating a Mapper Interface
import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.common.MySqlMapper; /** * @author suruomo * @date 2020/7/29 10:18 * @description: This interface cannot be scanned and should be separated from the self-defined Mapper. Any Mapper you define needs to inherit this interface. */ public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> { }Copy the code
4.2 Let the generated UserMapper interface inherit MyMapper interface
@Mapper
public interface UserMapper extends MyMapper<User> {
}
Copy the code
4.3 Creating a Public Service

The IService interface may:

import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author suruomo
 * @date 2020/7/29 13:26
 * @description:
 */
@Service
public interface IService<T> {

    List<T> selectAll();

    T selectByKey(Object key);

    int save(T entity);

    int delete(Object key);

    int updateAll(T entity);

    int updateNotNull(T entity);

    List<T> selectByExample(Object example);
Copy the code

Implement class BaseService:

import org.springframework.beans.factory.annotation.Autowired; import tk.mybatis.mapper.common.Mapper; import java.util.List; /** * @author suruomo * @date 2020/7/29 13:26 * @description: */ public class BaseService<T> implements IService<T> { @Autowired protected Mapper<T> mapper; public Mapper<T> getMapper() { return mapper; Override public List<T> selectAll() {return mapper.selectAll(); } @override public T selectByKey(Object key) { , according to the query by the primary key field method parameter must contain the complete primary key attribute, the query conditions using the equals sign return mapper. SelectByPrimaryKey (key); } @override public int save(T entity) {return mapper.insert(entity); } @ Override public int the delete Object (key) {/ / description: according to the primary key field to delete, method parameter must contain complete primary key attribute return mapper. DeleteByPrimaryKey (key); Entity} @ Override public int updateAll (T) {/ / description: according to the primary key update entities all fields, null values will be updated return mapper. UpdateByPrimaryKey (entity); } @ Override public int updateNotNull entity (T) {/ / updated according to the primary key attribute is not null value return mapper. UpdateByPrimaryKeySelective (entity); } @override public List<T> selectByExample(Object example) { Return mapper.selectByExample(Example); }}Copy the code
4.4 Creating a User-defined Service

UserService interface:

import com.suruomo.springboot10mybatis.model.User;
import com.suruomo.springboot10mybatis.service.common.IService;

/**
 * @author suruomo
 * @date 2020/7/29 13:30
 * @description:
 */
public interface UserService extends IService<User> {
}
Copy the code

Implementation class:

import com.suruomo.springboot10mybatis.mapper.UserMapper;
import com.suruomo.springboot10mybatis.model.User;
import com.suruomo.springboot10mybatis.service.common.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;

/**
 * @author suruomo
 * @date 2020/7/29 13:31
 * @description:
 */
@Repository("userService")
public class UserServiceImpl extends BaseService<User> implements UserService{
}
Copy the code
4.5 test
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.suruomo.springboot10mybatis.model.User; import com.suruomo.springboot10mybatis.service.UserService; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import tk.mybatis.mapper.entity.Example; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; / * * * * / @ SpringBootTest test class Springboot10MybatisApplicationTests {@ Resource private UserService UserService; /** * @test void save() {User User = new User(); user.setUserId("susu"); user.setUserName("suruomo"); user.setEmail("[email protected]"); user.setSex("1"); user.setPassword("xMpCOKC5I4INzFCab3WEmw=="); userService.save(user); } @test void delete() {User User = new User(); user.setUserId("susu"); this.userService.delete(user); } @test void select(){String userId="a"; System.out.println(userService.selectByKey(userId).getEmail()); } @test void selectAll(){List<User> List =new ArrayList<>(); list=userService.selectAll(); for(User user:list){ System.out.println(user.getUserId()); }} @test void selectByExample(){example example = new example (user.class); example.createCriteria().andCondition("user_name like '%a%'"); List<User> userList = this.userService.selectByExample(example); for (User u : userList) { System.out.println(u.getUserName()); } / @test void updateAll(){User User = userservice.selectBykey (" ZXC "); User. SetLoginIp (" 127.0.0.1 "); userService.updateAll(user); @test void selectByPage(){pagehelper.startPage (1,2); List<User> list = userService.selectAll(); PageInfo<User> pageInfo = new PageInfo<User>(list); List<User> result = pageInfo.getList(); for (User u : result) { System.out.println(u.getUserName()); }} @test void selectByUserName(){String userName="b"; System.out.println(userService.selectByUserName(userName)); }}Copy the code