MyBatis 使用手册
共 24814字,需浏览 50分钟
·
2020-12-11 11:05
越来越多的企业已经将 MyBatis 使用到了正式的生产环境,本文就使用 MyBatis 的几种方式提供简单的示例,以及如何对数据库密码进行加密,目前有以下章节:
单独使用 MyBatis 集成 Spring 框架 集成 Spring Boot 框架 Spring Boot 配置数据库密码加密
1.单独使用
引入 MyBatis 依赖,单独使用,版本是3.5.6
引入依赖
org.mybatis
mybatis
3.5.6
mysql
mysql-connector-java
8.0.19
添加mybatis-config.xml
"1.0" encoding="UTF-8" ?>
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
"cacheEnabled" value="false" />
"multipleResultSetsEnabled" value="true" />
"mapUnderscoreToCamelCase" value="true" />
"localCacheScope" value="STATEMENT" />
"tk.mybatis.simple.model" />
"development">
"development">
type="JDBC">
"" value=""/>
type="UNPOOLED">
"driver" value="com.mysql.cj.jdbc.Driver"/>
"url" value="jdbc:mysql://localhost:3306/gsfy_user?useUnicode=true&characterEncoding=UTF-8&useSSL=false"/>
"username" value="user"/>
"password" value="password"/>
"tk.mybatis.simple.mapper"/>
开始使用
Model类
tk.mybatis.simple.model.DbTest.java
package tk.mybatis.simple.model;
public class DbTest {
public Integer id;
public String text;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
return "DbTest{" +
"id=" + id +
", text='" + text + '\'' +
'}';
}
}
Mapper接口
tk.mybatis.simple.mapper.DbTestMapper
package tk.mybatis.simple.mapper;
import tk.mybatis.simple.model.DbTest;
public interface DbTestMapper {
DbTest queryById(Integer id);
}
XML映射文件
XML映射文件请放于Mapper接口所在路径下,保证名称相同
tk/mybatis/simple/mapper/DbTestMapper.xml
"1.0" encoding="UTF-8"?>
"-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
"tk.mybatis.simple.mapper.DbTestMapper">
执行示例
package tk.mybatis.simple;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import tk.mybatis.simple.mapper.DbTestMapper;
import java.io.IOException;
import java.io.Reader;
public class MyBatisHelper {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// MyBatis的配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 创建一个 sqlSessionFactory 工厂类
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
public static void main(String[] args) {
// 创建一个 SqlSession 会话
SqlSession sqlSession = MyBatisHelper.getSqlSession();
// 获取 DbTestMapper 接口的动态代理对象
DbTestMapper dbTestMapper = sqlSession.getMapper(DbTestMapper.class);
// 执行查询
System.out.println(dbTestMapper.queryById(1).toString());
}
}
2.集成Spring
在 Spring 项目中,使用 MyBatis 的模板,请注意 Spring 的版本为5.2.10.RELEASE
日志框架使用Log4j2(推荐),版本为2.13.3
,性能高于logback和log4j
我的项目模板 Git 地址
工程结构图
其中 jquery.min.js
文件可以去官网下载
引入依赖
"1.0" encoding="UTF-8"?>
"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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
tk.mybatis.simple
mybatis-spring
war
3.5.6
2.11.3
1.8
UTF-8
org.springframework
spring-framework-bom
5.2.10.RELEASE
<type>pomtype>
import
org.apache.logging.log4j
log4j-bom
2.13.3
import
<type>pomtype>
org.mybatis
mybatis-spring
1.3.2
org.mybatis
mybatis
${mybatis.version}
mysql
mysql-connector-java
8.0.19
com.alibaba
druid
1.2.3
com.github.pagehelper
pagehelper
5.2.0
com.github.jsqlparser
jsqlparser
3.2
javax.servlet
servlet-api
2.5
provided
javax.servlet.jsp
jsp-api
2.1
provided
javax.servlet
jstl
1.2
org.springframework
spring-context
org.springframework
spring-jdbc
org.springframework
spring-tx
org.springframework
spring-aop
org.aspectj
aspectjweaver
1.8.2
javax.annotation
javax.annotation-api
1.2
javax.transaction
javax.transaction-api
1.2
org.springframework
spring-web
org.springframework
spring-webmvc
com.fasterxml.jackson.core
jackson-databind
${jackson.version}
com.fasterxml.jackson.core
jackson-core
${jackson.version}
com.fasterxml.jackson.core
jackson-annotations
${jackson.version}
org.apache.logging.log4j
log4j-core
org.apache.logging.log4j
log4j-api
org.apache.logging.log4j
log4j-web
org.apache.logging.log4j
log4j-slf4j-impl
org.apache.logging.log4j
log4j-1.2-api
org.apache.logging.log4j
log4j-jcl
org.slf4j
slf4j-api
1.7.7
com.lmax
disruptor
3.4.2
commons-fileupload
commons-fileupload
1.4
commons-io
commons-io
2.8.0
commons-codec
commons-codec
1.15
study-ssm
maven-compiler-plugin
<source>1.8source>
1.8
UTF-8
src/main/java
**/*.properties
**/*.xml
false
src/main/resources/META-INF/spring
spring-mybatis.xml
spring-mvc.xml
false
src/main/resources
**/*.properties
**/*.xml
false
添加spring-mvc.xml
"1.0" encoding="UTF-8"?>
"http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
"tk.mybatis.simple" />
"mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
"supportedMediaTypes">
text/html;charset=UTF-8
"org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter ">
"messageConverters">
"multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
"defaultEncoding" value="utf-8" />
"maxUploadSize" value="104857600" />
"maxInMemorySize" value="40960" />
"resolveLazily" value="true"/>
"org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
"favorParameter" value="true" />
"parameterName" value="format"/>
"ignoreAcceptHeader" value="true" />
"mediaTypes">
json=application/json
xml=application/xml
html=text/html
"defaultContentType" value="text/html" />
"org.springframework.web.servlet.view.InternalResourceViewResolver">
"prefix" value="/WEB-INF/jsp/" />
"suffix" value=".jsp" />
"static/" mapping="/static/**"/>
添加mybatis-config.xml
"1.0" encoding="UTF-8" ?>
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
"cacheEnabled" value="false" />
"localCacheScope" value="STATEMENT" />
"lazyLoadingEnabled" value="true" />
"aggressiveLazyLoading" value="false" />
"useColumnLabel" value="true" />
"useGeneratedKeys" value="false" />
"mapUnderscoreToCamelCase" value="true" />
"tk.mybatis.simple.model" />
"com.github.pagehelper.PageInterceptor">
"helperDialect" value="mysql"/>
"offsetAsPageNum" value="true" />
"rowBoundsWithCount" value="true" />
"pageSizeZero" value="true" />
添加spring-mybatis.xml
"1.0" encoding="UTF-8"?>
"http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
"dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
"url" value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8"/>
"driverClassName" value="com.mysql.cj.jdbc.Driver"/>
"username" value="root"/>
"password" value="password"/>
"filters" value="stat,log4j,wall"/>
"maxActive" value="20"/>
"minIdle" value="20"/>
"initialSize" value="5"/>
"maxWait" value="10000"/>
"timeBetweenEvictionRunsMillis" value="3600000"/>
"minEvictableIdleTimeMillis" value="120000"/>
"testWhileIdle" value="true"/>
"testOnBorrow" value="false"/>
"mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
"dataSource" ref="dataSource"/>
"configLocation" value="classpath:mybatis-config.xml"/>
"mapperLocations" value="classpath:tk/mybatis/simple/mapper/*.xml"/>
"org.mybatis.spring.mapper.MapperScannerConfigurer">
"basePackage" value="tk.mybatis.simple.mapper"/>
"sqlSessionFactoryBeanName" value="mySqlSessionFactory"/>
"txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
"dataSource" ref="dataSource"/>
"txManager"/>
"transactionAdvice" transaction-manager="txManager">
"insert*" rollback-for="java.lang.Exception"/>
"delete*" rollback-for="java.lang.Exception"/>
"update*" rollback-for="java.lang.Exception"/>
"*" read-only="true"/>
"transactionAdvice" pointcut="execution(* tk.mybatis.*.service..*Service*.*(..))"/>
添加log4j2.xml
"1.0" encoding="UTF-8"?>
"INFO" monitorInterval="30">
"Console" target="SYSTEM_OUT">
"INFO" onMatch="ACCEPT" onMismatch="DENY"/>
"%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"/>
"RollingFile" fileName="logs/trace.log"
append="true" filePattern="logs/$${date:yyyy-MM}/trace-%d{yyyy-MM-dd}-%i.log.gz">
"INFO" onMatch="ACCEPT" onMismatch="DENY"/>
"%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"/>
"100 MB"/>
"RollingErrorFile" fileName="logs/error.log"
append="true" filePattern="logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz">
"WARN" onMatch="ACCEPT" onMismatch="DENY"/>
"%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"/>
"100 MB"/>
"org.springframework" level="INFO"/>
"org.mybatis" level="INFO"/>
"INFO" includeLocation="true">
"Console"/>
"RollingFile"/>
"RollingErrorFile"/>
添加web.xml
"1.0" encoding="UTF-8"?>
"http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
Archetype Created Web Application
contextConfigLocation
classpath:spring-mybatis.xml
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
true
encoding
UTF-8
forceEncoding
true
encodingFilter
/*
org.springframework.web.context.ContextLoaderListener
org.springframework.web.util.IntrospectorCleanupListener
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
1
true
SpringMVC
/
index.jsp
开始使用
Model类
tk.mybatis.simple.model.DbTest.java
package tk.mybatis.simple.model;
public class DbTest {
public Integer id;
public String text;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
return "DbTest{" +
"id=" + id +
", text='" + text + '\'' +
'}';
}
}
Mapper接口
tk.mybatis.simple.mapper.DbTestMapper
package tk.mybatis.simple.mapper;
import tk.mybatis.simple.model.DbTest;
public interface DbTestMapper {
DbTest queryById(Integer id);
}
XML映射文件
XML映射文件请放于Mapper接口所在路径下,保证名称相同
tk/mybatis/simple/mapper/DbTestMapper.xml
"1.0" encoding="UTF-8"?>
"-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
"tk.mybatis.simple.mapper.DbTestMapper">
Controller类
package tk.mybatis.simple.controller;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.simple.mapper.DbTestMapper;
import tk.mybatis.simple.model.DbTest;
@Controller
@RequestMapping(value = "/test")
public class DbTestController {
private static final Logger logger = LogManager.getLogger(DbTestController.class);
@Autowired
private DbTestMapper dbTestMapper;
@GetMapping("/")
public String index() {
return "welcome";
}
@GetMapping("/query")
public ModelAndView query(@RequestParam("id") Integer id) {
DbTest dbTest = dbTestMapper.queryById(id);
logger.info("入参:{},查询结果:{}", id, dbTest.toString());
ModelAndView mv = new ModelAndView();
mv.setViewName("result");
mv.addObject("test", dbTest);
return mv;
}
}
index.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
"zh-CN">
"utf-8">
"X-UA-Compatible" content="IE=edge">
"viewport" content="width=device-width, initial-scale=1">
首页
Hello World!
welcome.jsp
<%--
Created by IntelliJ IDEA.
User: jingp
Date: 2019/6/5
Time: 15:17
To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
"zh-CN">
"utf-8">
"X-UA-Compatible" content="IE=edge">
"viewport" content="width=device-width, initial-scale=1">
查询
查询数据库
result.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
"zh-CN">
"utf-8">
"X-UA-Compatible" content="IE=edge">
"viewport" content="width=device-width, initial-scale=1">
结果
查询结果:${test.toString()}
运行程序
配置好Tomcat,然后启动就可以了,进入页面,点击开始测试,然后查询数据库就可以通过MyBatis操作数据库了
3.集成SpringBoot
引入依赖
"1.0" encoding="UTF-8"?>
"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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
org.springframework.boot
spring-boot-starter-parent
2.0.3.RELEASE
4.0.0
tk.mybatis.simple
mybatis-spring-boot
jar
1.8
UTF-8
org.apache.logging.log4j
log4j-bom
2.13.3
import
<type>pomtype>
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-logging
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
1.16.22
provided
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.4
mysql
mysql-connector-java
8.0.19
com.alibaba
druid-spring-boot-starter
1.2.3
com.github.pagehelper
pagehelper-spring-boot-starter
1.3.0
org.apache.logging.log4j
log4j-core
org.apache.logging.log4j
log4j-api
org.apache.logging.log4j
log4j-web
org.apache.logging.log4j
log4j-slf4j-impl
org.apache.logging.log4j
log4j-1.2-api
org.apache.logging.log4j
log4j-jcl
org.slf4j
slf4j-api
1.7.7
com.lmax
disruptor
3.4.2
com.alibaba
fastjson
1.2.54
basic
org.codehaus.mojo
appassembler-maven-plugin
1.10
unix
windows
lib
flat
conf
true
src/main/resources
true
${project.build.directory}/basic-assemble
com.fullmoon.study.Application
basic
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/app/dump
-Xmx512m
-Xms512m
org.apache.maven.plugins
maven-compiler-plugin
<source>1.8source>
1.8
src/main/resources
*.properties
*.xml
*.yml
false
src/main/resources/mapper
mapper/
*.xml
false
添加mybatis-config.xml
MyBatis 的配置文件
"1.0" encoding="UTF-8" ?>
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
"cacheEnabled" value="false" />
"localCacheScope" value="STATEMENT" />
"lazyLoadingEnabled" value="true" />
"aggressiveLazyLoading" value="false" />
"useColumnLabel" value="true" />
"useGeneratedKeys" value="false" />
"mapUnderscoreToCamelCase" value="true" />
添加application.yml
Spring Boot 的配置文件
server:
port: 9092
servlet:
context-path: /mybatis-spring-boot-demo
tomcat:
accept-count: 200
min-spare-threads: 200
spring:
application:
name: mybatis-spring-boot-demo
profiles:
active: test
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver # 不配置则会根据 url 自动识别
initial-size: 5 # 初始化时建立物理连接的个数
min-idle: 20 # 最小连接池数量
max-active: 20 # 最大连接池数量
max-wait: 10000 # 获取连接时最大等待时间,单位毫秒
validation-query: SELECT 1 # 用来检测连接是否有效的 sql
test-while-idle: true # 申请连接的时候检测,如果空闲时间大于 timeBetweenEvictionRunsMillis,则执行 validationQuery 检测连接是否有效
test-on-borrow: false # 申请连接时执行 validationQuery 检测连接是否有效
min-evictable-idle-time-millis: 120000 # 连接保持空闲而不被驱逐的最小时间,单位是毫秒
time-between-eviction-runs-millis: 3600000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
filters: stat,log4j,wall # 配置过滤器,stat-监控统计,log4j-日志,wall-防御 SQL 注入
connection-properties: 'druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000' # StatFilter配置,打开合并 SQL 功能和慢 SQL 记录
web-stat-filter: # WebStatFilter 配置
enabled: true
url-pattern: '/*'
exclusions: '*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*'
stat-view-servlet: # StatViewServlet 配置
enabled: true
url-pattern: '/druid/*'
reset-enable: false
login-username: druid
login-password: druid
aop-patterns: 'com.fullmoon.study.service.*' # Spring 监控配置
mybatis:
type-aliases-package: tk.mybatis.simple.model
mapper-locations: classpath:mapper/*.xml
config-location: classpath:mybatis-config.xml
pagehelper:
helper-dialect: mysql
reasonable: true # 分页合理化参数
offset-as-page-num: true # 将 RowBounds 中的 offset 参数当成 pageNum 使用
supportMethodsArguments: true # 支持通过 Mapper 接口参数来传递分页参数
# 测试环境
---
spring:
profiles: test
datasource:
druid:
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
username: root
password: password
注意上面 mybatis
的相关配置,XML 映射文件是存放于 classpath 下的 mapper 文件夹下面的
添加log4j2.xml
"1.0" encoding="UTF-8"?>
"INFO" monitorInterval="30">
"Console" target="SYSTEM_OUT">
"INFO" onMatch="ACCEPT" onMismatch="DENY"/>
"%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"/>
"RollingFile" fileName="logs/trace.log"
append="true" filePattern="logs/$${date:yyyy-MM}/trace-%d{yyyy-MM-dd}-%i.log.gz">
"INFO" onMatch="ACCEPT" onMismatch="DENY"/>
"%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"/>
"100 MB"/>
"RollingErrorFile" fileName="logs/error.log"
append="true" filePattern="logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz">
"WARN" onMatch="ACCEPT" onMismatch="DENY"/>
"%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"/>
"100 MB"/>
"org.springframework" level="INFO"/>
"org.mybatis" level="INFO"/>
"INFO" includeLocation="true">
"Console"/>
"RollingFile"/>
"RollingErrorFile"/>
开始使用
在 Spring Boot 项目的启动类上面添加 @MapperScan("tk.mybatis.simple.mapper")
注解,指定 Mapper 接口所在的包路径,启动类如下:
@SpringBootApplication
@EnableTransactionManagement
@MapperScan("tk.mybatis.simple.mapper")
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
}
然后在 classpath 下的 mapper 文件夹(根据 application.yml 配置文件中的定义)添加 XML 映射文件,即可开始使用 MyBatis了
其中 @EnableTransactionManagement
注解表示开启事务的支持(@SpringBootApplication
注解在加载容器的时候已经开启事务管理的功能了,也可不需要添加该注解)
在需要事务的方法或者类上面添加 @Transactional
注解即可,引入spring-boot-starter-jdbc
依赖,注入的是 DataSourceTransactionManager 事务管理器,事务的使用示例如下:
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public int insertFeedback(UserFeedbackInfo requestAddParam) {
try {
// ... 业务逻辑
} catch (Exception e) {
// 事务回滚
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return 0;
}
}
4.SpringBoot配置数据库密码加密?
4.1 借助Druid数据源
Druid 数据源支持数据库密码进行加密,在 Spring Boot 中配置方式如下:
加密数据库密码,通过 Druid 的 com.alibaba.druid.filter.config.ConfigTools
工具类对数据库密码进行加密(RSA 算法),如下:
public static void main(String[] args) throws Exception {
ConfigTools.main(new String[]{"you_password"});
}
或者执行以下命令:
java -cp druid-1.0.16.jar com.alibaba.druid.filter.config.ConfigTools you_password
输出:
privateKey:MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA6+4avFnQKP+O7bu5YnxWoOZjv3no4aFV558HTPDoXs6EGD0HP7RzzhGPOKmpLQ1BbA5viSht+aDdaxXp6SvtMQIDAQABAkAeQt4fBo4SlCTrDUcMANLDtIlax/I87oqsONOg5M2JS0jNSbZuAXDv7/YEGEtMKuIESBZh7pvVG8FV531/fyOZAiEA+POkE+QwVbUfGyeugR6IGvnt4yeOwkC3bUoATScsN98CIQDynBXC8YngDNwZ62QPX+ONpqCel6g8NO9VKC+ETaS87wIhAKRouxZL38PqfqV/WlZ5ZGd0YS9gA360IK8zbOmHEkO/AiEAsES3iuvzQNYXFL3x9Tm2GzT1fkSx9wx+12BbJcVD7AECIQCD3Tv9S+AgRhQoNcuaSDNluVrL/B/wOmJRLqaOVJLQGg==
publicKey:MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOvuGrxZ0Cj/ju27uWJ8VqDmY7956OGhVeefB0zw6F7OhBg9Bz+0c84RjzipqS0NQWwOb4kobfmg3WsV6ekr7TECAwEAAQ==
password:PNak4Yui0+2Ft6JSoKBsgNPl+A033rdLhFw+L0np1o+HDRrCo9VkCuiiXviEMYwUgpHZUFxb2FpE0YmSguuRww==
然后在 application.yml 中添加以下配置:
spring:
datasource:
druid:
password: ${password} # 加密后的数据库密码
filters: config # 配置 ConfigFilter ,通过它进行解密
# 提示需要对数据库密码进行解密
connection-properties: 'config.decrypt=true;config.decrypt.key=${publickey}'
publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJvQUB7pExzbzTpaQCCY5qS+86MgYWvRpqPUCzjFwdMgrBjERE5X5oojSe48IGZ6UtCCeaI0PdhkFoNaJednaqMCAwEAAQ==
这样就OK了,主要是在 ConfigFilter
过滤器中,会先对密码进行解密,然后再设置到 DataSource 数据源
4.2 借助Jasypt加密包
Jasypt是一个 Java 库,可以让开发人员将基本的加密功能添加到项目中,而无需对加密的工作原理有深入的了解
接下来讲述的在 Spring Boot 项目中如何使用Jasypt,其他使用方法请参考Jasypt Github地址
引入依赖
com.github.ulisesbocchio
jasypt-spring-boot-starter
3.0.3
添加注解
在启动类上面添加@EnableEncryptableProperties
注解,使整个 Spring 环境启用 Jasypt 加密功能,如下:
@SpringBootApplication
@EnableEncryptableProperties
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
}
获取密文
需要通过 Jasypt 官方提供的 jar 包进行加密,如下:
import com.ulisesbocchio.jasyptspringboot.properties.JasyptEncryptorConfigurationProperties;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.PBEConfig;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
/**
* @author jingping.liu
* @date 2020-11-20
* @description Jasypt 安全框架加密类工具包
*/
public class JasyptUtils {
/**
* 生成一个 {@link PBEConfig} 配置对象
*
* 注意!!!
* 可查看 Jasypt 全局配置对象 {@link JasyptEncryptorConfigurationProperties} 中的默认值
* 这里的配置建议与默认值保持一致,否则需要在 application.yml 中定义这里的配置(也可以通过 JVM 参数的方法)
* 注意 password 和 algorithm 配置项,如果不一致在启动时可能会解密失败而报错
*
* @param salt 盐值
* @return SimpleStringPBEConfig 加密配置
*/
private static SimpleStringPBEConfig generatePBEConfig(String salt) {
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
// 设置 salt 盐值
config.setPassword(salt);
// 设置要创建的加密程序池的大小,这里仅临时创建一个,设置 1 即可
config.setPoolSize("1");
// 设置加密算法, 此算法必须由 JCE 提供程序支持,默认值 PBEWITHHMACSHA512ANDAES_256
config.setAlgorithm("PBEWithMD5AndDES");
// 设置应用于获取加密密钥的哈希迭代次数
config.setKeyObtentionIterations("1000");
// 设置要请求加密算法的安全提供程序的名称
config.setProviderName("SunJCE");
// 设置 salt 盐的生成器
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
// 设置 IV 生成器
config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
// 设置字符串输出的编码形式,支持 base64 和 hexadecimal
config.setStringOutputType("base64");
return config;
}
/**
* 通过 {@link PooledPBEStringEncryptor} 进行加密密
*
* @param salt 盐值
* @param message 需要加密的内容
* @return 加密后的内容
*/
public static String encrypt(String salt, String message) {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig pbeConfig = generatePBEConfig(salt);
// 生成加密配置
encryptor.setConfig(pbeConfig);
System.out.println("----ARGUMENTS-------------------");
System.out.println("message: " + message);
System.out.println("salt: " + pbeConfig.getPassword());
System.out.println("algorithm: " + pbeConfig.getAlgorithm());
System.out.println("stringOutputType: " + pbeConfig.getStringOutputType());
// 进行加密
String cipherText = encryptor.encrypt(message);
System.out.println("----OUTPUT-------------------");
System.out.println(cipherText);
return cipherText;
}
public static String decrypt(String salt, String message) {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
// 设置解密配置
encryptor.setConfig(generatePBEConfig(salt));
// 进行解密
return encryptor.decrypt(message);
}
public static void main(String[] args) {
// 随机生成一个 salt 盐值
String salt = UUID.randomUUID().toString().replace("-", "");
// 进行加密
encrypt(salt, "message");
}
}
如何使用
直接在 application.yml 配置文件中添加 Jasypt 配置和生成的密文
jasypt:
encryptor:
password: salt # salt 盐值,需要和加密时使用的 salt 一致
algorithm: PBEWithMD5AndDES # 加密算法,需要和加密时使用的算法一致
string-output-type: hexadecimal # 密文格式,,需要和加密时使用的输出格式一致
spring:
datasource:
druid:
username: root
password: ENC(cipherText) # Jasypt 密文格式:ENC(密文)
“salt 盐值也可以通过 JVM 参数进行设置,例如:-Djasypt.encryptor.password=salt
”
启动后,Jasypt 会先根据配置将 ENC(密文)
进行解密,然后设置到 Spring 环境中
作者:月圆吖
www.cnblogs.com/lifullmoon/p/14014660.html
最近熬夜给大家准备了515套Java代码,有一些是业务类的小项目,比如Java博客项目,也有脚手架、也有平时用一些的工具类、21套小程序代码,也有一些游戏类的项目。 扫以下二维码并回复“828”即可获取
或者在本公众号对话框回复【828】马上获取