This article is a sub-chapter of the personal development framework for SpringBoot2.1. Please read the personal development framework for SpringBoot2.1
Back-end project address: personal application development framework for SpringBoot2.1
Front-end project address: yWH-vuE-admin
Create a project structure for core submodules
Core module is mainly used to write business codes. It is better to put some common methods or classes into the common module. After modifying the above files, Core: com,ywh.core: click New-> Package to create package name, here I create my own custom, can be named according to their own custom.
Core is the core module of the project. The preliminary structure is as follows:
- Config — Put some configuration files
- Controller – The controller layer is placed under this package
- Dao – Put some of the operation interfaces to the database here
- Entity — The entity class of the business object
- Service – The interface and implementation class of the service layer. The Impl contains the implementation class of the service
- System – You can put system classes that core uses alone
- Mybatis -mappers — Puts the XML file of mybatis, which is created under resource
Druid is introduced
Creating a database connection is a time-consuming operation that can easily cause security risks to the database. Managing database connections can significantly affect the scalability and robustness of an overall application, affecting its performance metrics.
Druid is first and foremost a database connection pool, but it is more than just a database connection pool. It also includes a ProxyDriver, a set of built-in JDBC component libraries, and a SQLParser. Druid supports all jdbc-compliant databases, including Oracle, MySql, Derby, Postgresql, SQLServer, H2, and more. Druid provides special optimizations for Oracle and MySql, such as PSCache memory usage optimization for Oracle and ping detection optimization for MySql. Druid offers significant advantages in monitoring, scalability, stability, and performance. Druid provides an extended FILter-chain API that lets you write your own filters to intercept any JDBC method and do anything from performance monitoring to SQL auditing to username and password encryption to logging.
Reference:
-
Druid of the lot
-
Druid FAQ collection
Configure Druid in the project
Mysql > Druid > application dev. Yml > Druid > application dev. Yml > application dev. Most of the default configurations are in the YML file and I wrote a comment to make it easy to understand. If you want to customize the configuration, you can refer to Druid’s GitHub documentation. The JDBC dependency is added here because to connect to the database, you need a driver to do the connection, which can be removed after adding MyBatisPlus.
<! -- Druid connection pool dependency -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<! Mysql driver dependencies get the latest version without adding the version number -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<! -- JDBC driver dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>2.1.1. RELEASE</version>
</dependency>
Copy the code
Yml file content. The following content is omitted. For details, see application-dev.yml
Driver-class-name: com.mysql.jdbc.driver This driver is deprecated using a new version of com.mysql.cj.jdbc.driver
The console tells us to automatically find the appropriate driver for us, usually without manual loading, so I comment out
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
Initialize Druid
druid:
Mysql database address
url: JDBC: mysql: / / 127.0.0.1:3306 / ywh_code? useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
#driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
Monitor the user name and password of the page as well as the page address
stat-view-servlet:
login-username: admin
login-password: admin
enabled: true
url-pattern: /druid/*
Copy the code
After good Durid configuration, we can visit http://localhost:8082/core/druid/login.html. My port number is 8082 because I configured context-path in application.yml: / core, so I visit the address is the address above, if there is no configuration, the default is http://localhost:8080/druid/login.html, login account and password are admin, monitoring interface I will not put up.
Integrated Mybatis – Plus
Mybatis-Plus is an enhanced version of Mybatis. Mybatis-Plus is an enhanced version of Mybatis. Mybatis-Plus is an enhanced version of Mybatis. So it is perfectly compatible with Mybatis, and also supports automatic generation of code for you, and supports a large number of CRUD interfaces for users. There are also a lot of excellent cases using MybaitS-Plus.
- Mybatis-Plus official documentation
Mybatis-Plus is configured in the project
First, introduce Mybatis-Plus dependencies in parent POP. XML, configure core application-dev.yml file, Add @mapperscan (basePackages = “com.ywh.**.dao”) to the startup class as required on the official website to scan all interfaces in your DAO package automatically injected into Spring’s IOC container for us to use. The dependencies are: mybatis-plus-boot-starter, freemarker, velocity. The last two are used as templates for code generation, which will be used later. You can search online for these two dependencies and check their introduction.
<! -- mybatisPlus dependencies -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.6</version>
</dependency>
<! -- Freemarke engine dependencies introduced -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<! -- Velocity engine dependencies -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
Copy the code
application-dev.yml
mybatis-plus:
mapper-locations: classpath*:/mybatis-mappers/*
# MyBaits alias package scan path, through this property can be registered for the package class alias, after registration in Mapper corresponding XML file can directly use the class name, instead of using the fully qualified class name
type-aliases-package: com.ywh.core.entity
Automatic camelback naming of database tables and entity classes
configuration:
map-underscore-to-camel-case: true
Copy the code
@SpringBootApplication(scanBasePackages = "com.ywh")
/** * global configuration, scan the DAO interface under the specified package, do not write on each DAO interface@MapperNote * /
@MapperScan(basePackages = "com.ywh.**.dao")
public class CoreApplication {
public static void main(String[] args) { SpringApplication.run(CoreApplication.class, args); }}Copy the code
The test case
Create a user table in yWH_code and insert some data for query.
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT ' ' COMMENT 'User name'.`age` tinyint(3) unsigned NOT NULL COMMENT 'User age'.`gender` tinyint(3) unsigned NOT NULL COMMENT 'User gender',
PRIMARY KEY (`id`))ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
INSERT INTO `user` VALUES ('1'.'ywh'.'22'.'1');
INSERT INTO `user` VALUES ('2'.'lry'.'22'.'1');
INSERT INTO `user` VALUES ('3'.'whp'.'26'.'0');
Copy the code
Write the corresponding database properties in the ExampleEntity Entity class in the Entity package we created earlier, write a query method in the ExampleDao interface class in the DAO layer, and test our configuration in the SpringBoot test class. The properties in the Entity class have their own GET. Set methods, I’m using Lombok’s annotations to help us automatically produce get set methods. Lombok’s idea plugin is installed in the parent pom.xml. If this is too cumbersome, you can generate your own GET and set methods.
<! -- Lombok's dependency -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
Copy the code
In idea, choose File->Settings->Plugins to search for lombok Plugin and install it. If there is a connection timeout error, you can click Lombok Plugin in IDEA to download the lombok Plugin and install it locally.
Entity class
import lombok.Data;
/** * CreateTime: 2018-12-09 18:24 * ClassName: ExampleEntity * Package: com.ywh.core. Entity * Describe: * Test entity class **@author YWH
*/
@Data
public class ExampleEntity {
private Integer id;
private String name;
private String age;
private String gender;
}
Copy the code
The dao interface
import com.ywh.core.entity.ExampleEntity;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/** * CreateTime: 2018-12-09 18:25 * ClassName: ExampleDao * Package: com.ywh.core. Dao * Describe: * test ExampleDao layer persistence layer **@author YWH
*/
public interface ExampleDao {
@Select("select * from user")
List<ExampleEntity> findAll(a);
}
Copy the code
SpringBoot test class
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CoreApplicationTests {
@Autowired
private ExampleDao exampleDao;
@Test
public void contextLoads(a) { List<ExampleEntity> all = exampleDao.findAll(); System.out.println(all); }}Copy the code
After running the test method, the output is:
[ExampleEntity(id=1, name=ywh, age=22, gender=1), ExampleEntity(id=2, name=lry, age=22, gender=1), ExampleEntity(id=3, name=whp, age=26, gender=0)]
Copy the code
MybatisPlus code generator
Integrated with MybatisPlus, the code generator in the core function of MybatisPlus can help us greatly improve work efficiency without creating a lot of repetitive work. AutoGenerator is the code generator of MyBatis-Plus. The AutoGenerator can quickly generate the code of Entity, Mapper, Mapper XML, Service, Controller and other modules, greatly improving the development efficiency. The generated code is only a general method we have set in advance. We still had to write the business code ourselves, but it helped us a lot.
- MybatisPlus official code generator configuration
I put this function under the Common module, so we need to divide the structure of the common submodule.
- Base: stores basic controllers and services
- Config: Puts some configuration classes
- Entity: Put some basic entity classes
- Mapper: you can put the basic mapper. XML file
- Exception: Can put our custom exception class
- Utils: Put some common utility classes
- Create templates in the Resources directory and put the templates we’ll use later.
With the directory structure in place, we create a mybatisplus.properties file to hold the variables we often change without having to change them in the code:
OutputDir =/ywh-starter-core/ SRC /main/ Java # setParent=com.ywh.core If you have any changes in the generated code Before not confirm don't change to be true or to the file cover missing code fileOverride = false # address url = JDBC: database mysql: / / 127.0.0.1:3306 / ywh_code? UseUnicode =true&useSSL=false&characterEncoding= UTf8 &serverTimezone=GMT%2B8 # Database Driver driverClass= com.mysql.cj.jdbc.driver Mapper. XML file generation path mapperPath=/ywh-starter-core/src/main/resources/mybatis-mappers/Copy the code
Configuring template Content
The generated code needs to be generated from the template. MybatisPlus officially uses Velocity as the default template. It also provides another template called Freemarker.
- Velocity: Velocity is a Java-based templating engine. It allows anyone to use a simple and powerful templating language to reference objects defined in Java code.
- Freemarker: Freemarker is a template engine: a generic tool for generating output text based on templates and data to change.
- Freemarker’s syntax is as follows :Freemaker FTL directive common tags and syntax
In com.baomidou.mybatis -plus-Generator there is a templates folder and the official templates file is provided. We use the Freemarker template engine, with the suffix.ftl. Copy all the files with.ftl into the templates we created, but if you don’t want to change it yourself, you can skip this step and just use the default.
Controller.java.ftl: Because there is too much code, only one example is posted here. For more details, please go to my Git. A freemarker template
package ${package.Controller};
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${table.entityName};
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage?? >
import ${superControllerClassPackage};
</#if>/** * CreateTime: ${date} * ClassName: ${table.controllerName} * Package: ${package.Controller} * Describe: * ${table.comment! } Front-end controller * @author YWH */<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if controllerMappingHyphenStyle?? >${table.controllerName}<#else>${controllerMappingHyphen}</#if>")
<#if superControllerClass?? >
public class ${table.controllerName} extends ${superControllerClass}<${table.serviceName},${table.entityName}> {
<#else>
public class ${table.controllerName} {
</#if>
private static final Logger log = LoggerFactory.getLogger(${table.controllerName}.class);
@Autowired
private ${table.serviceName} service;
}
Copy the code
Write auto-generated code
Next we can use the example provided by the official CodeGenerator to create our own CodeGenerator class, under utils, I will not introduce the code details, you can read according to the official document (the address is posted above), although the generated code is empty, However, since we inherit the classes provided by MybatisPlus, we already have a large number of CRUD interfaces for our use. For specific CRUD interfaces, please refer to the official CRUD interface of MybatisPlus
- MybatisPlus automatically generates code
package com.ywh.common.utils;
/** * CreateTime: 2018-12-16 13:52 * ClassName: CodeGenerator * Package: com.ywh.common.utils * Describe: * Code generator for MybatisPlus * *@author YWH
*/
public class CodeGenerator {
/** * Get the contents of the console *@paramTip What the console enters *@return* /
public static String scanner(String tip){
Scanner scanner = new Scanner(System.in);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Please enter" + tip + ":");
System.out.println(stringBuilder.toString());
if(scanner.hasNext()){
String ipt = scanner.next();
if(StringUtils.isNotEmpty(ipt)){
// Return if the input is not null
returnipt; }}throw new MybatisPlusException("Please enter the correct one" + tip +! "" ");
}
public static void main(String[] args) {
ResourceBundle resource = ResourceBundle.getBundle("myBatisPlus");
String outPutDir = resource.getString("outputDir");
Boolean fileOverride = false;
if("true".equals(resource.getString("fileOverride"))){
fileOverride = true;
}
String url = resource.getString("url");
String driverClass = resource.getString("driverClass");
String userName = resource.getString("userName");
String passWord = resource.getString("passWord");
String setParent = resource.getString("setParent");
// Code generator. Because the code is too long, please go to Github to see the specific code}}Copy the code
The effect is as follows: