Home > Java > javaTutorial > How to implement single table operation by integrating Mapper in springboot

How to implement single table operation by integrating Mapper in springboot

王林
Release: 2023-05-11 15:31:14
forward
768 people have browsed it

1. Framework Maven deployment and installation

After downloading the framework source code, execute mvn clean install in the project root path to install it into the local maven library. If you need to share and use Nexus private server, add distributionManagement configuration in the root path pom.xml file, specify the Nexus warehouse distribution address, and use mvn clean deploy to install to the remote maven warehouse, 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>
Copy after login

specified above The repository needs to have corresponding account configuration in all maven configuration files settings.xml (id needs to correspond one to one), 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>
Copy after login

2. pom.xml configuration

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

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

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

  3. ##The project inherits cn.jboost.springboot:spring- boot-parent (using druid connection pool)

The pom.xml configuration of the three methods is 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>
Copy after login
Introduce the driver dependency of mysql or postgresql (others) according to the situation The database does not yet support type conversion and has not been tested)

3. Configure the data source

If you use the druid connection pool, configure it in application.yml In the file, add the following data source configuration (recommended)

spring:
datasource:
druid:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8
username: root
password:
# 自定义配置
initialSize: 2 # 初始化大小
minIdle: 1 # 最小连接
maxActive: 5 # 最大连接
druidServletSettings:
allow: 127.0.0.1
deny:
loginUsername: admin
loginPassword: Passw0rd
resetEnable: true
druidFilterSettings:
exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
maxWait: 60000 # 配置获取连接等待超时的时间
timeBetweenEvictionRunsMillis: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
minEvictableIdleTimeMillis: 300000 # 配置一个连接在池中最小生存的时间,单位是毫秒
validationQuery: SELECT 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true # 打开PSCache,并且指定每个连接上PSCache的大小
maxPoolPreparedStatementPerConnectionSize: 20
filters: stat #,wall(添加wall代码里不能直接拼接sql,druid有sql注入校验) # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
useGlobalDataSourceStat: true # 合并多个DruidDataSource的监控数据
Copy after login
If you do not use a connection pool, the configuration is relatively simple, as follows


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
Copy after login

4. Define the corresponding domain and mapper , service, controller objects at each layer

Take demo as an example (see resources/schema.sql for demo database script), 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
}
}
Copy after login
needs to be added The @Table annotation specifies the database table name. You can implement auto-increment primary key by inheriting AutoIncrementKeyBaseDomain, or implement UUID primary key by UUIDKeyBaseDomain. If you customize other types of primary keys, inherit BaseDomain.

The framework's Service layer general method implementation BaseService only supports single-column primary keys and does not support composite primary keys (and it is not recommended to use composite primary keys)

The framework defaults to mapping complex type attributes such as List and Map to For mysql's json type or postgresql's jsonb type, if a certain attribute does not require mapping, you can add the @Transient annotation; for enumeration types, you need to add @ColumnType to specify the jdbcType.

Dao layer defines UserMapper,

@Repository
public interface UserMapper extends BaseMapper<User> {
}
Copy after login
BaseMapper implements the functions of adding, deleting, modifying and batch inserting a single table by default. If you need to define complex queries, you can define them in this interface and then use mapper xml file writing and implementation.

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


@Service
public class UserService extends BaseService<Integer, User> {
@Transactional
public void createWithTransaction(User user){
create(user);
//用于测试事务
throw new RuntimeException("抛出异常,让前面的数据库操作回滚");
}
}
Copy after login
The controller layer defines UserController, which inherits The general interface of BaseController (please view the source code for details)

@RestController
@RequestMapping("/user")
public class UserController extends BaseController<Integer, User> {
}
Copy after login
is as above. You only need to define the interface or class corresponding to each layer and inherit the basic interface or class to complete the user's basic addition, deletion, modification and query functions. No need to write A line of specific implementation code.

5. Test and run

The example provides unit tests for two new users. Refer to the SpringbootTkmapperApplicationTests class

to run. Run it 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)

The above is the detailed content of How to implement single table operation by integrating Mapper in springboot. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template