Database access is an essential part of the web application. Today the most common database ORM framework Hibernate and Mybatis, Hibernate looks in more traditional IT enterprise use, and Mybatis is used more often in Internet companies. General Mapper ( https://github.com/abel533/Mapper) is based Mybatis, additions or deletions will change search a single table implemented by a general method, to reduce the SQL open source framework written, and that there is also the open source mapper-spring-boot -starter provided. On this basis, we added some customized content, in order to achieve a greater degree of reuse.
Framework Source Address: https://github.com/ronwxy/base-spring-boot (continuously updated to improve welcomed the Follow, Star)
Demo Source Address: https://github.com/ronwxy/springboot-demos/tree/ master / springboot-tkmapper
On the basis of the open source mapper-spring-boot-starter on the increase of the following:
- Add some Java types and database types of conversion processing class for MySQL database and PostgreSQL databases, such as the json type List, Map Type and MySQL database conversion process
- For Domain, Mapper, Service, Controller layers is encapsulated, the basic CRUD universal function layers
- It provides automatic configuration of the connection pool based druid
- Other adjustments, such default mapping the complex property (mainly List, Map type, other types need to customize the custom conversion processing class), enumerated as a simple type of treatment
- It provides a parent project, some common framework for the integration of the actual project inheritable parent-dependent configuration simplifies (continuously updated sound)
The framework may be used based on the actual project springboot, simply configure the data source, can be introduced into the pool and the common function of connecting druid mapper, and the layers basic CRUD method.
how to use?
The procedures given below, reference Example: https://github.com/ronwxy/springboot-demos/tree/master/springboot-tkmapper
1. Deployment mounting frame Maven
After downloading source frame, the project root path of execution mvn clean install
may be mounted to a local library maven. If you need to share and take a Nexus PW, add pom.xml file in the root path distributionManagement
configuration, designated warehouse distribution Nexus address, use the mvn clean deploy
installation to the remote maven repository, such as
<distributionManagement> <repository> <id>nexus-releases</id> <url> http://ip:port/repository/maven-releases/ </url> </repository> <snapshotRepository> <id>nexus-snapshots</id> <url> http://ip:port/repository/maven-snapshots/ </url> </snapshotRepository> </distributionManagement>
The designated account repository must have the required configuration (id correspond required) all in settings.xml maven profile, such as
<servers> <server> <id>nexus-snapshots</id> <username>admin</username> <password>xxx</password> </server> <server> <id>nexus-releases</id> <username>admin</username> <password>xxx</password> </server> </servers>
2. pom.xml configuration
There are three ways to introduce the project in the framework of the database:
- Direct introduction cn.jboost.springboot: tkmapper-spring-boot-starter (not connection pool)
- Direct introduction cn.jboost.springboot: druid-spring-boot-starter (druid connection pool support)
- Project inheritance cn.jboost.springboot: spring-boot-parent (using a druid connection pool)
pom.xml arranged in three ways as follows
#第一种方式 <dependency> <groupId>cn.jboost.springboot</groupId> <artifactId>tkmapper-spring-boot-starter</artifactId> <version>1.2-SNAPSHOT</version> </dependency> #第二种方式 <dependency> <groupId>cn.jboost.springboot</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2-SNAPSHOT</version> </dependency> #第三种方式 <parent> <groupId>cn.jboost.springboot</groupId> <artifactId>spring-boot-parent</artifactId> <version>1.2-SNAPSHOT</version> <relativePath/> <!-- lookup parent from repository --> </parent>
The case of introducing the drive-dependent mysql or postgresql (Write a cast and another database support, not tested)
Configuration data source
If druid connection pool, then application.yml configuration file, add the following data source configuration (recommended)
the Spring: the DataSource: Druid: Driver-class-name: com.mysql.jdbc.Driver url: jdbc: MySQL: // localhost:? 3306 / = to true autoReconnect the Test & useUnicode = to true & characterEncoding = UTF-8 username: root password: # custom configuration initialSize: 2 # initial size minIdle: 1 # minimum connection maxActive: 5 # maximum connection druidServletSettings: the allow: 127.0.0.1 the deny: loginUsername: ADMIN loginPassword: Passw0rd resetEnable: to true druidFilterSettings: Exclusions: '* .js, * GIF,. * .jpg, *. png, * . css, *. ico, / druid / * ' maxWait: # 60000 configuration obtaining connection waiting timeout time timeBetweenEvictionRunsMillis: 60000 # long intervals once it is detected, the detection needs to close idle connections milliseconds minEvictableIdleTimeMillis: 300000 # configure a minimum connection time cell survival milliseconds validationQuery: the SELECT 'X' testWhileIdle: to true testOnBorrow: to false testOnReturn: to false poolPreparedStatements: true # open PSCache, and specifies the size of each connection PSCache maxPoolPreparedStatementPerConnectionSize: 20 after stat #, wall (wall adding the code can not be directly spliced sql, druid check has sql injection) configuration monitoring statistics # intercept filters, remove: filters sql monitoring interface can not be quantified, 'wall' for firewall connectionProperties: druid.stat.mergeSql = true; druid.stat.slowSqlMillis = 5000 # mergeSql opened by connectProperties property function; slow SQL record useGlobalDataSourceStat: merging a plurality of monitoring data DruidDataSource of true #
If no connection pool, the configuration is relatively simple, as
spring: datasource: url: jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8 username: root password: driver-class-name: com.mysql.jdbc.Driver
4. Define the appropriate domain, mapper, service, controller objects layers
To demo, for example (see script demo database resources / schema.sql), domain defines a User class,
@Table(name = "user") @Getter @Setter @ToString public class User extends AutoIncrementKeyBaseDomain<Integer> { private String name; @ColumnType(jdbcType = JdbcType.CHAR) private Gender gender; private List<String> favor; private Map<String, String> address; public enum Gender{ M, F } }
We need to add @Table
annotations to specify the name of the database table, through inheritance AutoIncrementKeyBaseDomain
to achieve increment primary keys, or UUIDKeyBaseDomain
to achieve UUID primary key, if other types of custom primary key is inherited BaseDomain
.
Service Framework Layer General method implemented
BaseService
only supports single primary key, does not support combination of a primary key (primary key combination not recommended)
Framework for default List, Map and other complex property is mapped to jsonb type json type of mysql or postgresql, if a property does not need maps, notes can be added @Transient; enumerated types to be added @ColumnType designated jdbcType.
dao layer defines UserMapper
,
@Repository public interface UserMapper extends BaseMapper<User> { }
BaseMapper
The default implementation of single-table additions and deletions to change search and bulk inserts and other functions. For the definition of complex queries can be defined in the interface, and then prepared to achieve by mapper xml file.
service layer defines UserService
inherited BaseService
common functions (see Specific source), the same method can be customized in the class
@Service public class UserService the extends BaseService < Integer , the User > { @Transactional public void createWithTransaction (the User User) { Create (User); // for testing transaction throw new RuntimeException ( "throws an exception, so that the front of the database Rollback "); } }
controller layer defines UserController
inherited BaseController
common interface (see Specific source)
@RestController @RequestMapping("/user") public class UserController extends BaseController<Integer, User> { }
As above, the respective layers only need to define a corresponding interface or class, or classes inheriting the interface, the user completes the basic CRUD function, not need to write one line of code specific implementation.
5. Test run
-
It provides two examples of the new user unit test, reference
SpringbootTkmapperApplicationTests
Class -
Run, run directly on the main class, and then open the browser http: // localhost: 8080 / user can list the unit test user created (other interface reference
BaseController
implementation)
6. Summary
This article describes the framework is based on tk.mybatis:mapper-spring-boot-starter
doing some custom extensions to achieve a greater degree of reuse. Can be used in the actual project development, the course if you encounter problems, may be concerned about the public number Feedback.
My personal blog address: http://blog.jboost.cn
my headline space: https://www.toutiao.com/c/user/5833678517/#mid=1636101215791112
my github address: HTTPS: // github .com / ronwxy
my micro-channel public number: jboost-ksxy
————————————————————————————————————————
I welcome attention to the micro-channel public number, timely access to the latest share