Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize single table operation by integrating Mapper in springboot

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is a detailed introduction to "how to realize single table operation by integrating Mapper in springboot". The content is detailed, the steps are clear, and the details are properly handled. I hope this article "how to realize single table operation by integrating Mapper in springboot" can help you solve your doubts. Let's go deeper and learn new knowledge together with the ideas of Xiaobian.

1. Framework Maven Deployment Installation

After downloading the framework source code, execute mvn clean install under the project root path to install it into the local maven library. If sharing is required and Nexus private server is installed, add distributionManagement configuration to the root path pom.xml file, specify Nexus repository distribution address, and install it to remote maven repository using mvn clean deploy, such as

nexus-releaseshttp://ip:port/repository/maven-releases/nexus-snapshotshttp://ip:port/repository/maven-snapshots/

The repository specified above needs to have corresponding account configuration in all configuration files settings.xml of maven (id needs to correspond one by one), such as

nexus-snapshotsadminxxxnexus-releasesadminxxx

2. pom.xml configuration

There are three ways to introduce this database framework into a project:

Directly introduce cn.jboost.springboot:tkmapper-spring-boot-starter (no connection pool)

Directly introduce cn.jboost.springboot:druid-spring-boot-starter (druid connection pool support)

The project inherits cn.jboost.springboot:spring-boot-parent (druid connection pool is used)

The pom.xml configuration for the three ways is as follows

#First way cn.jboost.springboottkmapper-spring-boot-starter1.2-SNAPSHOT#Second way cn.jboost.springbootdruid-spring-boot-starter1.2-SNAPSHOT#Third way cn.jboost.springbootspring-boot-parent1.2-SNAPSHOT

Introduce driver dependency of mysql or postgresql according to the situation (other databases have not done type conversion support yet, and have not been tested)

3. configure data source

If using druid connection pool, add the following data source configuration to the application.yml configuration file (recommended)

spring:datasource:druid:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/test? autoReconnect=true&useUnicode=true&characterEncoding= utf-8 username: rootpassword:#custom configurationinitialSize: 2 #initialSize minIdle: 1 #minconnectionmaxActive: 5 #maxconnectiondruidServletSettings:allow: 127.0.0.1deny:loginUsername: adminloginPassword: Passw0rdresetEnable: truedruidFilterSettings:exclusions: '*.js,*.gif,*. jpg, *.png,*.css,*.ico,/druid/*'maxWait: 60000 #Configure timebetweenEvictionRunsMillis: 60000 #Configure how often to detect idle connections that need to be closed, in milliseconds minEvictableIdleTimeMillis: 300000 #Configure the minimum survival time of a connection in the pool, in milliseconds validationQuery: SELECT 'x'testWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true #Open PSCache and specify the size of PSCache on each connection maxPoolPreparedStatementPerConnectionSize: 20filters: stat #,wall (sql cannot be directly spliced in the added wall code, druid has sql injection check)#Configure the filters for monitoring statistics interception. After removing the monitoring interface sql cannot be counted,'wall' is used for firewall connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 #Enable mergeSql function through connectProperties attribute; slow SQL record useGlobalDataSourceStat: true #Merge monitoring data from multiple DruidDataSources

If connection pooling is not used, the configuration is relatively simple, as follows

spring:datasource:url: jdbc:mysql://localhost:3306/test? autoReconnect=true&useUnicode=true&characterEncoding=utf-8username: rootpassword:driver-class-name: com.mysql.jdbc.Driver

4. Define corresponding domain, mapper, service, controller objects at each level

Take demo as an example (see resources/schema.sql for demo database scripts), domain defines a User class,

@Table(name = "user")@Getter@Setter@ToStringpublic class User extends AutoIncrementKeyBaseDomain {private String name;@ColumnType(jdbcType = JdbcType.CHAR)private Gender gender;private List favor;private Map address;public enum Gender{M,F}}

You need to add @Table annotation to specify database table name. You can implement self-increment primary key by inheriting AutoIncrementKeyBaseDomain, or UUIDKeyBaseDomain to implement UUID primary key. If you customize other types of primary keys, inherit BaseDomain.

BaseService, a general method for Service layer implementation of the framework, only supports single primary key, not combined primary key (combined primary key is not recommended).

By default, the framework maps complex type attributes such as List and Map to json type of mysql or jsonb type of postgresql. If a certain attribute does not need mapping, you can add @Transient annotation; enumeration type needs to add @ColumnType to specify jdbcType.

dao layer defines UserMapper

@Repositorypublic interface UserMapper extends BaseMapper {}

BaseMapper implements the functions of adding, deleting, querying and batch inserting of single tables by default. If you need to define complex queries, you can define them in this interface, and then write them through the mapper xml file.

The service layer defines UserService, which inherits the common functions of BaseService (see the source code for details). You can also customize methods in this class.

@Servicepublic class UserService extends BaseService {@Transactionalpublic void createWithTransaction(User user){create(user);//Used to test transactions throw new RuntimeException("throw exception, roll back previous database operation");}}

The controller layer defines UserController, inheriting the common interface of BaseController (see source code for details)

@RestController@RequestMapping("/user")public class UserController extends BaseController {}

As mentioned above, only need to define the interface or class corresponding to each layer, inherit the basic interface or class, and complete the basic user's add, delete and check function, without writing a specific line of implementation code.

5. Testing, operation

The sample provides unit tests for two new users, see SpringbootTkmapperApplicationTests class

Run, run directly on the main class, and then open http://localhost:8080/user in the browser to list the users created in the unit test (refer to BaseController implementation for other interfaces)

Read here, this article "how to achieve single table operation through integration Mapper in springboot" has been introduced, want to master the knowledge points of this article also need to be used by yourself to understand, if you want to know more about the relevant content of the article, welcome to pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report