Mybatis – Plus is an integrated mybatis- Plus system with spring Boot. After that, I will expand why MYbatis – Plus is used instead of JDBC directly. Briefly, in fact, big data projects use JDBC instead of ORM framework, because transaction management in the framework and call reflection API during execution will affect performance. I don’t care about small projects, just develop them as fast as possible. All right, let’s cut the crap and get right to the code.
Add dependencies to POM.xml
<? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < the parent > < groupId > org. Springframework. Boot < / groupId > The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.5.2 < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name> Demo </name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <! --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <! Mybatis --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis -- plus-boot-starter</artifactId> The < version > 3.4.0 < / version > < / dependency > <! -- Mybatis - Generator core dependencies, --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> The < version > 3.4.0 < / version > < / dependency > <! <dependency> <groupId>org.apache.velocity</groupId> < artifactId > velocity < / artifactId > < version > 1.7 < / version > < / dependency > < the dependency > <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*</include> </includes> </resource> </resources> </build> </project>Copy the code
Note that I added the Resources node to the build node above, because I am not used to putting mybatis XML file under the project resource, so I added the Resources node to the POM to type the XML into the JAR package.
Application. Yml is as follows:
server: port: 5211 servlet: context-path: /demo spring: application: name: demo jmx: default-domain: demo jackson: Date - the format: MM - dd yyyy - HH: MM: ss time - zone: GMT + 8 datasource: url: JDBC: mysql: / / 192.168.16.130:3306 / demo? useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver hikari: pool-name: demo minimum-idle: 5 idle-timeout: 120000 max-lifetime: 120000 maximum-pool-size: 30 connection-timeout: 6000 connection-test-query: select 1 mybatis-plus: configuration: map-underscore-to-camel-case: true mapper-locations: classpath:com/example/demo/mapper/*.xmlCopy the code
Paging plug-in
@configuration public class MybatisPlusConfig {/** ** Public MybatisPlusInterceptor MybatisPlusInterceptor () {MybatisPlusInterceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; }}Copy the code
Code custom generates classes
package com.example.demo.generator; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.StrategyConfig; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; Public class Generator {public void generateCode(String tableName) {// specify the packageName. String packageName = "com.example.demo"; // user -> UserService, set to true: user -> IUserService Boolean serviceNameStartWithI = false; String[] tableNames = new String[]{tableName}; generateByTables(serviceNameStartWithI, packageName, tableNames); } @param serviceNameStartWithI default to false @param packageName packageName @param tableNames table name @author Terry */ private void generateByTables(boolean serviceNameStartWithI, String packageName, String... TableNames) {// Set DataSourceConfig DataSourceConfig = getDataSourceConfig(); // StrategyConfig StrategyConfig = getStrategyConfig(tableNames); GlobalConfig GlobalConfig = getGlobalConfig(serviceNameStartWithI); PackageConfig PackageConfig = getPackageConfig(packageName); // Automatically generate atuoGenerator(dataSourceConfig, strategyConfig, globalConfig, packageConfig); } /** * integration ** @param dataSourceConfig configure data source * @param strategyConfig Policy configuration * @param config Global variable configuration * @param packageConfig * @author Terry */ private void atuoGenerator(DataSourceConfig DataSourceConfig, StrategyConfig StrategyConfig, GlobalConfig config, PackageConfig packageConfig) { new AutoGenerator().setGlobalConfig(config).setDataSource(dataSourceConfig).setStrategy(strategyConfig) .setPackageInfo(packageConfig).execute(); } /** * set packageName ** @param packageName packageName of the parent path * @return PackageConfig packageName * @author Terry */ private PackageConfig getPackageConfig(String packageName) { return new PackageConfig().setParent(packageName).setXml("mapper").setMapper("dao").setController("controller") .setEntity("entity"); } /** * Global configuration ** @param serviceNameStartWithI false * @return GlobalConfig * @author Terry */ private GlobalConfig getGlobalConfig(boolean serviceNameStartWithI) { GlobalConfig globalConfig = new GlobalConfig(); GlobalConfig. SetBaseColumnList (true). SetBaseResultMap (true). SetActiveRecord (false). SetAuthor (" ligang ") / / set the output path .setOutputDir(getOutputDir("demo")).setFileOverride(true); if (! ServiceNameStartWithI) {/ / set the service name globalConfig. SetServiceName (" % sService "); } return globalConfig; } /** * returns project path ** @param projectName projectName * @return project path * @author Terry */ private String getOutputDir(String) projectName) { String path = this.getClass().getClassLoader().getResource("").getPath(); int index = path.indexOf(projectName); return path.substring(1, index) + projectName + "/src/main/java/"; } /** * policy configuration ** @param tableNames table name * @return StrategyConfig * @author Terry */ private StrategyConfig getStrategyConfig(String... TableNames) {return new StrategyConfig().setcapitalMode (true).setentitylombokModel (false) // NamingStrategy from database table to file. SetNaming (namingstrategy.underline_to_camel) // // generating table name, multiple tableNames pass array. SetInclude (tableNames); } /** * DataSourceConfig ** @author Terry */ private DataSourceConfig getDataSourceConfig() { String dbUrl = "JDBC: mysql: / / 192.168.16.132:3306 / demo? useSSL=false"; return new DataSourceConfig().setDbType(DbType.MYSQL).setUrl(dbUrl).setUsername("root") .setPassword("summer123").setDriverName("com.mysql.cj.jdbc.Driver"); } @param packageName packageName @param tableNames table name @author Terry */ @suppresswarnings ("unused") private void generateByTables(String packageName, String... tableNames) { generateByTables(true, packageName, tableNames); } public static void main(String[] args) { new Generator().generateCode("demo"); }}Copy the code
Add test table
CREATE TABLE `demo` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `sex` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `age` int(11) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;Copy the code
Add the @mapperscan annotation to the startup class, taking the directory of our DAO interface
@SpringBootApplication @MapperScan("com.example.demo.dao") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}Copy the code
After executing the main method of Generator, the corresponding Model, Mapper, DAO, Service, ServiceImpl, and Controller can be created automatically. This article does not cover automatic generation tools
public class Demo implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String name;
private String sex;
private Integer age;
}
Copy the code
Creating the DAO Interface
public interface DemoMapper extends BaseMapper<Demo> {
}
Copy the code
Create a service
public interface DemoService extends IService<Demo> {
}
Copy the code
Create an implementation of the service
@Service
public class DemoServiceImpl extends ServiceImpl<DemoMapper, Demo> implements DemoService {
}
Copy the code
Mybatis – Plus has encapsulated some general methods for us below, so you can try them out for yourself and leave a comment below if you have any questions.
// Insert a record (select field, insert policy) Boolean save(T entity); // Insert (batch) Boolean saveBatch(Collection<T> entityList); Boolean saveBatch(Collection<T> entityList, int batchSize); Boolean saveOrUpdate(T entity); SaveOrUpdate (T) Boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper); Boolean saveOrUpdateBatch(Collection<T> entityList); Boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize); Boolean remove(Wrapper<T> queryWrapper); Boolean removeById(Serializable ID); Boolean removeByMap(Map<String, Object> columnMap); Boolean removeByIds(Collection<? extends Serializable> idList); Sqlset Boolean update(Wrapper<T> UpdateWrapper); Boolean update(T updateEntity, Wrapper<T> whereWrapper); Boolean updateById(T entity); Boolean updateBatchById(Collection<T> entityList); Boolean updateBatchById(Collection<T> entityList, int batchSize); // Query T getById(Serializable ID) according to ID; // Query a record according to Wrapper. Last ("LIMIT 1") T getOne(Wrapper<T> queryWrapper); T getOne(Wrapper<T> queryWrapper, Boolean throwEx); Map<String, Object> getMap(Wrapper<T> queryWrapper); <V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper); List<T> List (); List<T> List (Wrapper<T> queryWrapper); Collection<T> listByIds(Collection<? extends Serializable> idList); // Query (based on columnMap condition) Collection<T> listByMap(Map<String, Object> columnMap); List<Map<String, Object>> listMaps(); List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper); List<Object> listObjs(); <V> listObjs(Function<? super Object, V> mapper); List<Object> listObjs(Wrapper<T> queryWrapper); List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper); IPage<T> page; IPage<T> page; IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper); IPage<Map<String, Object>> pageMaps(IPage<T> page); IPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper); Int count(); Int count(Wrapper<T> queryWrapper);Copy the code
Next, we will talk about Mybatis – Generator, QueryWrapper of MyBatis – Plus and multi-data source of Mybatis – Plus, which will be divided into three parts. Thank you for your likes.
Join QQ group, let’s progress together.