preface
Some common knowledge points about Mybatis, summed up a mind map, share with you.MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all of the JDBC code and the work of setting parameters and fetching result sets. MyBatis can configure and map primitive types, interfaces, and Java POJOs (Plain Old Java Objects) to records in the database via simple XML or annotations. More and more enterprises have used MyBatis to the formal production environment, this article on the use of MyBatis several ways to provide simple examples, and how to encrypt the database password, there are the following chapters:
Use MyBatis alone
Integrating the Spring Framework
Integrate the Spring Boot framework
Spring Boot Configures database password encryption
One, use alone
Introduced MyBatis dependency, used alone, version 3.5.6
Introduction of depend on
<dependencies> <! -- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> The < artifactId > mybatis < / artifactId > < version > 3.5.6 < / version > < / dependency > <! -- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> < artifactId > mysql connector - Java < / artifactId > < version > 8.0.19 < / version > < / dependency > < / dependencies >Copy the code
Add mybatis – config. XML
<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE configuration PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> <! -- The location of the plugins in the configuration file must be correct, otherwise an error will be reported, in the following order: properties? , settings? , typeAliases? , typeHandlers? , objectFactory? ,objectWrapperFactory? , plugins? , environments? , databaseIdProvider? , mappers? -- > <! < Settings > <! Setting name="cacheEnabled" value="false" /> <! - for unknown SQL queries, allowed to return to a different result sets in order to achieve the effect of general - > < setting name = "multipleResultSetsEnabled" value = "true" / > <! <setting name="mapUnderscoreToCamelCase" value="true" /> <! <setting name="localCacheScope" -- MyBatis uses the Local Cache mechanism to prevent circular references and speed up repeated nested queries --> value="STATEMENT" /> </settings> <! -- Specifies that the entity class under the path supports aliases (default entity class name, lowercase first letter), <package name="tk.mybatis. Simple. Model "/> </typeAliases> <! > <environment default="development"> <environment ID ="development"> <transactionManager type="JDBC"> <property name="" value=""/> </transactionManager> <! <dataSource type="UNPOOLED"> <property name="driver" value=" com.mysql.cj.jdbc.driver "/> <property name="url" value="jdbc:mysql://localhost:3306/gsfy_user? useUnicode=true& characterEncoding=UTF-8& useSSL=false"/> <property name="username" value="user"/> <property name="password" value="password"/> </dataSource> </environment> </environments> <! Mapper --> <mappers> <package name="tk.mybatis. Simple. Mapper "/> </mappers> </configuration>Copy the code
Begin to use
Model class
tk.mybatis.simple.model.DbTest.java
Copy the code
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 + '\'' + '}'; }}Copy the code
Mapper interfaces
tk.mybatis.simple.mapper.DbTestMapper
Copy the code
package tk.mybatis.simple.mapper;
import tk.mybatis.simple.model.DbTest;
public interface DbTestMapper {
DbTest queryById(Integer id);
}
Copy the code
XML mapping file
The XML mapping file must be saved in the path where the Mapper interface resides, and its name must be the same
tk/mybatis/simple/mapper/DbTestMapper.xml
Copy the code
<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE mapper PUBLIC "- / / mybatis.org//DTD mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > < mapper namespace="tk.mybatis.simple.mapper.DbTestMapper"> <select id="queryById" parameterType="int" resultType="DbTest"> SELECT db_test_id AS id, db_test_text AS text FROM db_test WHERE db_test_id = #{id, jdbcType=INTEGER} </select> </mapper>Copy the code
Execute the sample
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; The static {try {/ / MyBatis config file Reader Reader = Resources. GetResourceAsReader (" MyBatis - config. XML "); 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) {/ / create a SqlSession session SqlSession SqlSession. = MyBatisHelper getSqlSession (); DbTestMapper DbTestMapper = sqlsession.getmapper (dbTestmapper.class); Println (dbTestMapper.queryById(1).toString()); }}Copy the code
Second, integrate Spring
In the Spring project, use the MyBatis template. Note that the Spring version is 5.2.10.release
The logging framework uses Log4j2 (recommended), version 2.13.3, which performs better than LogBack and log4J
Git address of my project template
Engineering structure drawing
MyBatis-Spring- examplestructure jquery.min.js file can be downloaded from the official website
Introduction of depend on
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="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">
<modelVersion>4.0.0</modelVersion>
<groupId>tk.mybatis.simple</groupId>
<artifactId>mybatis-spring</artifactId>
<packaging>war</packaging>
<properties>
<!-- MyBatis 版本号 -->
<mybatis.version>3.5.6</mybatis.version>
<!-- Jackson 版本号 -->
<jackson.version>2.11.3</jackson.version>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>5.2.10.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>2.13.3</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- MyBatis 相关 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!-- druid 数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.3</version>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>3.2</version>
</dependency>
<!--web-->
<!--支持 Servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!--支持 JSP-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<!--支持 JSTL-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Spring 上下文,核心依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<!--Spring JDBC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<!--Spring 事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<!--Spring 面向切面编程-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<!--spring-aop 依赖-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.2</version>
</dependency>
<!--JSR 250 公共注解-->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.2</version>
</dependency>
<!--Java 事务接口-->
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<version>1.2</version>
</dependency>
<!--Spring Web 核心-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<!--Spring MVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!--spring mvc-json依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log4j2 start -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</dependency>
<!-- 保证 web 应用正常清理 log 资源 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
</dependency>
<dependency> <!-- 桥接:slf4j 到 log4j2 的桥梁 -->
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</dependency>
<dependency> <!-- 后向兼容:log4j1.x 平滑升级到 log4j2 -->
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-1.2-api</artifactId>
</dependency>
<dependency> <!-- 桥接:commons-logging(jcl) 到 log4j2 的桥梁 -->
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jcl</artifactId>
</dependency>
<!-- slf4j 日志切面,相当于一个适配器 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<!-- 高性能并发编程框架 log4j2 使用 -->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.4.2</version>
</dependency>
<!-- log4j2 end -->
<!-- 上传组件包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
</dependencies>
<build>
<finalName>study-ssm</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources/META-INF/spring</directory>
<includes>
<include>spring-mybatis.xml</include>
<include>spring-mvc.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
Copy the code
Add spring – the MVC. XML
<? The XML version = "1.0" encoding = "utf-8"? > <beans xmlns="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 "> <! <context:component-scan base-package="tk.mybatis. Simple "/> <! -- Avoid AJAX execution in IE Returns a JSON download file -- > < bean id = "mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html; charset=UTF-8</value> </list> </property> </bean> <! -- Enable annotations for SpringMVC To complete the request and annotate the POJO mapping - > < bean class = "org. Springframework. Web. Servlet. MVC. Method. The annotation. RequestMappingHandlerAdapter" > <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <! </list> </property> </bean> <! -- Configuration file upload, if you do not use file upload can not be configured, <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <! Property name="defaultEncoding" value=" UTF-8 "/> <! <property name="maxUploadSize" value="104857600" /> <property name="maxInMemorySize" value="40960" /> <! <property name="resolveLazily" value="true"/> </bean> <! -- Define the ViewResolver and configure multiple orders that need to be sorted using the order attribute. InternalResourceViewResolver last - > < bean class = "org. Springframework. Web. Accept. ContentNegotiationManagerFactoryBean" > <property name="favorParameter" value="true" /> <property name="parameterName" value="format"/> <property name="ignoreAcceptHeader" value="true" /> <property name="mediaTypes"> <value> <! Tell the view parser, The returned type is JSON format --> json=application/json XML =application/ XML HTML =text/ HTML </value> </property> <property name="defaultContentType" value="text/html" /> </bean> <! - define the jump of the file before the suffix, view name parser - > < bean class = "org. Springframework. Web. Servlet. The InternalResourceViewResolver" > <! Automatically prefix and suffix the action method return string. <property name="prefix" value="/ web-INF/JSP /" /> <property name="suffix" value=".jsp" /> </bean> <! MVC :annotation-driven /> <! < MVC :default-servlet-handler/> <! < MVC :resources location="static/" mapping="/static/**"/> </beans>Copy the code
Add mybatis – config. XML
<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE configuration PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> <! -- The location of the plugins in the configuration file must be correct, otherwise an error will be reported, in the following order: properties, settings, typeAliases, plugins, objectFactory, objectWrapperFactory, reflectorFactory, environments, databaseIdProvider, typeHandlers, mappers --> <! < Settings > <! Setting name="cacheEnabled" value="false" /> <! -- Enable level 1 caching, SESSION (default) Setting name="localCacheScope" value="STATEMENT" /> <! The association tag in the resultMap tag allows lazy loading --> <! <setting name="lazyLoadingEnabled" value="true" /> <! -- Set the loading mode of associated objects, close the intrusive lazy loading, do not query the associated objects when accessing the main object, but only query the associated objects when actually accessing the associated objects, to improve performance --> <! -- In versions 3.4.1 and earlier, the aggressive query function is enabled by default, which does not implement associated query but only when the user logs in to the main object. --> <setting name=" slogs "value="false" /> <! <setting name="useColumnLabel" value="true" /> <! Setting name="useGeneratedKeys" value="false" /> <! -- Whether to enable Auto-Camel Case mapping <setting name="mapUnderscoreToCamelCase" value="true" /> </ Settings > <! -- Specifies that the entity class under the path supports aliases (default entity class name is all lowercase), <typeAliases> <package name="tk.mybatis. Simple. Model "/> </typeAliases> <plugins> <! -- PageHelper pagination plugin https://github.com/pagehelper/Mybatis-PageHelper --> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <! <property name="helperDialect" value="mysql"/> <! -- The default is false, which is valid when using RowBounds as a paging parameter. When this parameter is set to true, the offset argument in RowBounds is used as pageNum, <property name="offsetAsPageNum" value="true" /> <! -- The default is false, which is valid when using RowBounds as a paging parameter. When this parameter is set to true, count queries are performed using RowBounds paging --> <property name="rowBoundsWithCount" value="true" /> <! -- The default value is false. When set to true, pageSize=0 or rowbounds. limit =0 will query all results (equivalent to no paging query, <property name="pageSizeZero" value="true" /> </plugin> </plugins> </configuration>Copy the code
Add spring – mybatis. XML
<? The XML version = "1.0" encoding = "utf-8"? > <beans xmlns="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"> <! - define a data source - > < bean id = "dataSource" class = "com. Alibaba. Druid. Pool. DruidDataSource" init - method = "init" Destroy - method = "close" > < property name = "url" value = "JDBC: mysql: / / 127.0.0.1:3306 / test? useUnicode=true& characterEncoding=utf8"/> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="username" value="root"/> <property name="password" value="password"/> <property name="filters" value="stat,log4j,wall"/> <! <property name="maxActive" value="20"/> <property name="minIdle" value="20"/> <! <property name="initialSize" value="5"/> <! <property name="maxWait" value="10000"/> <! - perform a free connection within a specified time interval collector - > < property name = "timeBetweenEvictionRunsMillis" value = "3600000" / > <! - connecting the idle in the pool after a specified time be recycled - > < property name = "minEvictableIdleTimeMillis" value = "120000" / > < property name = "testWhileIdle" value="true"/> <property name="testOnBorrow" value="false"/> </bean> <! - Spring and MyBatis integration -- > < bean id = "mySqlSessionFactory" class = "org. MyBatis. Spring. SqlSessionFactoryBean" > < property name="dataSource" ref="dataSource"/> <! <property name="configLocation" value=" clasSPath: MyBatis -config.xml"/> <! - automatic scanning XML mapping file -- > < property name = "mapperLocations" value = "classpath: tk/mybatis/simple/mapper / *. XML" / > < / bean > <! - through MapperScannerConfigurer classes automatically scan Mapper interfaces - > < bean class = "org. Mybatis. Spring. Mapper. MapperScannerConfigurer" > <! <property name="basePackage" value="tk.mybatis. Simple. Mapper "/> <! - refer to the above SqlSessionFactoryBean object - > < property name = "sqlSessionFactoryBeanName" value = "mySqlSessionFactory" / > < / bean > <! - the transaction manager - > < bean id = "txManager" class = ". Org. Springframework. JDBC datasource. DataSourceTransactionManager "> <! < dataSource name="dataSource" /> </ dataSource > <! <tx:annotation- Driven transaction-manager="txManager"/> <! <tx:advice ID ="transactionAdvice" transaction-manager="txManager"> < TX: Attributes > <tx:method name="insert*" rollback-for="java.lang.Exception"/> <tx:method name="delete*" rollback-for="java.lang.Exception"/> <tx:method name="update*" rollback-for="java.lang.Exception"/> <tx:method name="*" read-only="true"/> </tx:attributes> </tx:advice> <! < AOP :advisor advice-ref="transactionAdvice" pointcut="execution(*) tk.mybatis.*.service.. *Service*.*(..) )"/> </aop:config> <aop:aspectj-autoproxy/> </beans>Copy the code
Add log4j2. XML
<? The XML version = "1.0" encoding = "utf-8"? > <configuration status="INFO" monitorInterval="30"> <appenders> <! - refer to official address: https://logging.apache.org/log4j/2.x/ - > <! <Console name="Console" target="SYSTEM_OUT"> <! -- <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/> <! - the format of the log - > < PatternLayout pattern = "% d {MM - dd yyyy - HH: MM: ss, SSS} : % 4 p % t (% F, % L) - % m % n" / > < / Console > <! -- Define a log input file RollingFile, > <RollingFile name="RollingFile" fileName="logs/trace.log" append="true" filePattern="logs/$${date:yyyy-MM}/trace-%d{yyyy-MM-dd}-%i.log.gz"> <! --> <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/> <! - the format of the log - > < PatternLayout pattern = "% d {MM - dd yyyy - HH: MM: ss, SSS} : % 4 p % t (% F, % L) - % m % n" / > < Policies > <TimeBasedTriggeringPolicy/> <SizeBasedTriggeringPolicy size="100 MB"/> </Policies> </RollingFile> <! -- Define a log input file RollingErrorFile, --> <RollingFile name="RollingErrorFile" fileName="logs/error.log" append="true" filePattern="logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz"> <! --> <ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY"/> <! - the format of the log - > < PatternLayout pattern = "% d {MM - dd yyyy - HH: MM: ss, SSS} : % 4 p % t (% F, % L) - % m % n" / > < Policies > <TimeBasedTriggeringPolicy/> <SizeBasedTriggeringPolicy size="100 MB"/> </Policies> </RollingFile> </appenders> <loggers> <! <logger name="org. springFramework "level="INFO"/> <logger name="org. Mybatis" level="INFO"/> <root level="INFO" includeLocation="true"> <appender-ref ref="Console"/> <appender-ref ref="RollingFile"/> <appender-ref ref="RollingErrorFile"/> </root> </loggers> </configuration>Copy the code
Add web. XML
<? The XML version = "1.0" encoding = "utf-8"? > <web-app xmlns:xsi="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" > <display-name>Archetype Created Web Application</display-name> <! <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <! Spring provides the CharacterEncodingFilter that filters for each browser request. > <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <! -- ContextLoaderListener is heard when the container (Tomcat, Jetty) is started, and the contextInitialized() method is called. Initialize Root WebApplicationContext --> <! -- Declare Spring Web container listener --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <! -- Prevent Spring memory overflow listener --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <! DispatcherServlet is a Servlet, so you can configure multiple dispatcherservlets --> < Servlet > <! During the initialization of DispatcherServlet, the framework will look for the configuration file named [servlet-name]-servlet.xml in the Web-INF folder of the Web application. --> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <! -- The program runs from web.xml and is loaded in the following order: Context-param -> Listener -> Filter -> Structs -> Servlet Sets the loading order of the web. XML file when it is started (1 indicates that the Servlet is initialized first when the container is started, Load-on-startup means that the Servlet is created when the current Web application is loaded. <async-supported>true</async-supported> </servlet> <servlet-mapping> <! The Servlet name is SpringMVC. There can be multiple DispatcherServlets. Each DispatcherServlet has its own WebApplicationContext. It's stored both in the ServletContext and in the Request object. The ApplicationContext is the core Context of Spring that we usually refer to as the Context, Spring puts beans in this container, which can be retrieved by the getBean method if needed --> <servlet-name>SpringMVC</servlet-name> <! Servlet intercepts matching rules, optional configuration: *. Do, *. Action, *. HTML / *, /, / XXX, don't allow: / * - > < url - the pattern > / < / url - the pattern > < / servlet mapping - > < welcome - file - the list > <! <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>Copy the code
Begin to use
Model class
tk.mybatis.simple.model.DbTest.java
Copy the code
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 + '\'' + '}'; }}Copy the code
Mapper interfaces
tk.mybatis.simple.mapper.DbTestMapper
Copy the code
package tk.mybatis.simple.mapper;
import tk.mybatis.simple.model.DbTest;
public interface DbTestMapper {
DbTest queryById(Integer id);
}
Copy the code
XML mapping file
The XML mapping file must be saved in the path where the Mapper interface resides, and its name must be the same
tk/mybatis/simple/mapper/DbTestMapper.xml
Copy the code
<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE mapper PUBLIC "- / / mybatis.org//DTD mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > < mapper namespace="tk.mybatis.simple.mapper.DbTestMapper"> <select id="queryById" parameterType="int" resultType="DbTest"> SELECT db_test_id AS id, db_test_text AS text FROM db_test WHERE db_test_id = #{id, jdbcType=INTEGER} </select> </mapper>Copy the code
The Controller class
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(" input: {}, query result: {}", id, dbtest.toString ()); ModelAndView mv = new ModelAndView(); mv.setViewName("result"); mv.addObject("test", dbTest); return mv; }}Copy the code
index.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html; charset=UTF-8" language="java" %> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, </title> </head> <body> <h3>Hello World! </h3> <form method="get" action="<c:url value="/test/"/>"> <button class="btn btn-default" type="submit"> Start testing < span > < / span > < / button > < / form > < / body > < / HTML >Copy the code
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" %> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, Initial-scale =1"> <title> query </title> </head> <body> <h3> <form method="get" action="<c:url Value ="/test/query"/>"> <div class="input-group"> <span class="input-group-addon">ID: </span> <input type="number" name="id" class="form-control" required> </div> <button class="btn btn-default" Query type = "submit" > < span > < / span > < / button > < / form > < script SRC = ".. /.. /static/jquery.min.js"></script> </body> </html>Copy the code
result.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html; charset=UTF-8" language="java" %> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, </title> </head> <body> <h4> ${test.toString()}</h4> <form method="post" action="<c:url value="/"/>"> <button class="btn btn-default" type="submit"> <span> </span> </button> </form> <script SRC =".. /.. /static/jquery.min.js"></script> </body> </html>Copy the code
To run the program
Configure Tomcat, and then start it, enter the page, click start test, and then query the database can operate the database through MyBatis
3. Integrate SpringBoot
Introduction of depend on
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="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">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>tk.mybatis.simple</groupId>
<artifactId>mybatis-spring-boot</artifactId>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>2.13.3</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Spring Boot 核心包,包括自动装配,日志,以及YAML文件解析 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 提供全栈的 WEB 开发特性,包括 Spring MVC 依赖和 Tomcat 容器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 提供通用单元测试依赖,包括 JUnit, Hamcrest , Mockito -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- lombok 工具 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.22</version>
<scope>provided</scope>
</dependency>
<!-- MyBatis 相关 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!-- druid 数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log4j2 start -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</dependency>
<!-- 保证 web 应用正常清理 log 资源 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
</dependency>
<dependency> <!-- 桥接:slf4j 到 log4j2 的桥梁 -->
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</dependency>
<dependency> <!-- 后向兼容:log4j1.x 平滑升级到 log4j2 -->
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-1.2-api</artifactId>
</dependency>
<dependency> <!-- 桥接:commons-logging(jcl) 到 log4j2 的桥梁 -->
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jcl</artifactId>
</dependency>
<!-- slf4j 日志切面,相当于一个适配器 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<!-- 高性能并发编程框架 log4j2 使用 -->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.4.2</version>
</dependency>
<!-- log4j2 end -->
<!-- JSON 工具 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
</dependencies>
<build>
<finalName>basic</finalName>
<!-- 配置相关插件 -->
<plugins>
<!-- appassembler-maven-plugin -->
<!-- mvn clean package appassembler:assemble -Dmaven.test.skip=true -Dmaven.javadoc.skip=true -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>appassembler-maven-plugin</artifactId>
<version>1.10</version>
<configuration>
<!-- 生成linux和windows两种执行脚本 -->
<platforms>
<platform>unix</platform>
<platform>windows</platform>
</platforms>
<!-- jar存放的目录 -->
<repositoryName>lib</repositoryName>
<!-- jar包存放在指定目录的规则,默认是${groupId}/${artifactId}的目录格式,flat表示直接把jar放到目录下 -->
<repositoryLayout>flat</repositoryLayout>
<!-- 配置文件存放的目录 -->
<configurationDirectory>conf</configurationDirectory>
<!-- copy配置文件到上面目录 -->
<copyConfigurationDirectory>true</copyConfigurationDirectory>
<!-- 从哪里copy配置文件(默认src/main/config) -->
<configurationSourceDirectory>src/main/resources</configurationSourceDirectory>
<includeConfigurationDirectoryInClasspath>true</includeConfigurationDirectoryInClasspath>
<!-- ${project.build.directory}:target, 文件存放的根目录 -->
<assembleDirectory>${project.build.directory}/basic-assemble</assembleDirectory>
<programs>
<program>
<!-- 启动类 -->
<mainClass>com.fullmoon.study.Application</mainClass>
<!-- 生成的文件名称:basic.sh -->
<id>basic</id>
<!-- 配置JVM参数 -->
<jvmSettings>
<extraArguments>
<!--<extraArgument>-server</extraArgument>-->
<extraArgument>-XX:+HeapDumpOnOutOfMemoryError</extraArgument>
<extraArgument>-XX:HeapDumpPath=/app/dump</extraArgument>
<extraArgument>-Xmx512m</extraArgument>
<extraArgument>-Xms512m</extraArgument>
</extraArguments>
</jvmSettings>
</program>
</programs>
</configuration>
</plugin>
<!-- 编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
<!-- 指定 resources -->
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>*.properties</include>
<include>*.xml</include>
<include>*.yml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources/mapper</directory>
<targetPath>mapper/</targetPath>
<includes>
<include>*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
Copy the code
Add mybatis – config. XML
MyBatis configuration file
<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE configuration PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> <! -- The location of the plugins in the configuration file must be correct, otherwise an error will be reported, in the following order: properties, settings, typeAliases, plugins, objectFactory, objectWrapperFactory, reflectorFactory, environments, databaseIdProvider, typeHandlers, mappers --> <! < Settings > <! Setting name="cacheEnabled" value="false" /> <! -- Enable level 1 caching, SESSION (default) Setting name="localCacheScope" value="STATEMENT" /> <! The association tag in the resultMap tag allows lazy loading --> <! <setting name="lazyLoadingEnabled" value="true" /> <! -- Set the loading mode of associated objects, close the intrusive lazy loading, do not query the associated objects when accessing the main object, but only query the associated objects when actually accessing the associated objects, to improve performance --> <! -- In versions 3.4.1 and earlier, the aggressive query function is enabled by default, which does not implement associated query but only when the user logs in to the main object. --> <setting name=" slogs "value="false" /> <! <setting name="useColumnLabel" value="true" /> <! Setting name="useGeneratedKeys" value="false" /> <! -- Whether to enable Auto-Camel Case mapping <setting name="mapUnderscoreToCamelCase" value="true" /> </ Settings > </configuration>Copy the code
Add application. Yml
Spring Boot configuration file
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 # Initial-size: 5 # Number of physical connections established during initialization min-idle: 20 # Number of minimum connection pools max-active: Validation: SELECT 1 from SQL test-while-idle to check whether a connection is valid True # application connection testing, if free time is more than timeBetweenEvictionRunsMillis, execute validationQuery test connection is valid test - on - borrow: Min-evictable-idle-time-millis: min-evictable-idle-time-millis: Time-between-eviction -runs-millis: 3600000 # Configuration interval for detection of idle connections that need to be closed, in milliseconds filters: Stat,log4j,wall # Config filter, stat- monitor statistics, log4j-log,wall - defense SQL injection connection-properties: 'druid.stat. Druid.stat. SlowSqlMillis =5000' # statStatFilter ' true url-pattern: '/*' exclusions: '*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*' stat-view-servlet: # StatViewServlet configuration enabled: true url-pattern: '/druid/*' reset-enable: false login-username: druid login-password: Druid aop - patterns: 'com. Fullmoon. Study. Service. *' # Spring monitoring configuration 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 # True # replace the offset argument in RowBounds with pageNum: true # supportMethodsArguments: true # support pagination parameters passing through Mapper interface parameters # test environment -- spring: Profiles: test the datasource: druid: url: JDBC: mysql: / / 127.0.0.1:3306 / test? UseUnicode = true& characterEncoding=utf8 username: root password: passwordCopy the code
The XML mapping file is stored in the mapper folder of classpath
Add log4j2. XML
<? The XML version = "1.0" encoding = "utf-8"? > <configuration status="INFO" monitorInterval="30"> <appenders> <! - refer to official address: https://logging.apache.org/log4j/2.x/ - > <! <Console name="Console" target="SYSTEM_OUT"> <! -- <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/> <! - the format of the log - > < PatternLayout pattern = "% d {MM - dd yyyy - HH: MM: ss, SSS} : % 4 p % t (% F, % L) - % m % n" / > < / Console > <! -- Define a log input file RollingFile, > <RollingFile name="RollingFile" fileName="logs/trace.log" append="true" filePattern="logs/$${date:yyyy-MM}/trace-%d{yyyy-MM-dd}-%i.log.gz"> <! --> <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/> <! - the format of the log - > < PatternLayout pattern = "% d {MM - dd yyyy - HH: MM: ss, SSS} : % 4 p % t (% F, % L) - % m % n" / > < Policies > <TimeBasedTriggeringPolicy/> <SizeBasedTriggeringPolicy size="100 MB"/> </Policies> </RollingFile> <! -- Define a log input file RollingErrorFile, --> <RollingFile name="RollingErrorFile" fileName="logs/error.log" append="true" filePattern="logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz"> <! --> <ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY"/> <! - the format of the log - > < PatternLayout pattern = "% d {MM - dd yyyy - HH: MM: ss, SSS} : % 4 p % t (% F, % L) - % m % n" / > < Policies > <TimeBasedTriggeringPolicy/> <SizeBasedTriggeringPolicy size="100 MB"/> </Policies> </RollingFile> </appenders> <loggers> <! <logger name="org. springFramework "level="INFO"/> <logger name="org. Mybatis" level="INFO"/> <root level="INFO" includeLocation="true"> <appender-ref ref="Console"/> <appender-ref ref="RollingFile"/> <appender-ref ref="RollingErrorFile"/> </root> </loggers> </configuration>Copy the code
Begin to use
Add @mapperscan (“tk.mybatis. Simple. mapper”) annotation to the Boot class of the Spring Boot project to specify the package path of the mapper interface.
@SpringBootApplication @EnableTransactionManagement @MapperScan("tk.mybatis.simple.mapper") public class Application { public static void main(String[] args){ SpringApplication.run(Application.class, args); }}Copy the code
You can start using MyBatis by adding the XML mapping file to the mapper folder in your CLASspath (as defined in the application.yml configuration file)
@ EnableTransactionManagement annotations are in favour of open transactions (@ SpringBootApplication annotations when loading the container has the function of the open transaction management, also don’t need to add the annotation)
In need of transaction method or class above add @ Transactional annotation, introducing spring – the boot – starter – JDBC dependence, injection DataSourceTransactionManager affairs manager, the transaction using the sample is as follows:
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public int insertFeedback(UserFeedbackInfo requestAddParam) { try { // ... Business logic} the catch (Exception e) {/ / transaction rollback TransactionAspectSupport. CurrentTransactionStatus (). The setRollbackOnly (); return 0; }}Copy the code
SpringBoot configuration database password encryption?
1. Use the Druid data source
Druid supports encryption of database passwords. Spring Boot supports encryption of database passwords.
Encrypted database password, through the Druid com. Alibaba. Druid. Filter. Config. ConfigTools tools for database password encryption algorithm (RSA), as follows:
public static void main(String[] args) throws Exception {
ConfigTools.main(new String[]{"you_password"});
}
Copy the code
Or run the following command:
Java - cp druid - 1.0.16. Jar com. Alibaba. Druid. Filter. Config. ConfigTools you_passwordCopy the code
Output:
privateKey:MIIBVgIBADANBgkqhkiG9w0BAQEFAASCAUAwggE8AgEAAkEA6+4avFnQKP+O7bu5YnxWoOZjv3no4aFV558HTPDoXs6EGD0HP7RzzhGPOKmpL Q1BbA5viSht+aDdaxXp6SvtMQIDAQABAkAeQt4fBo4SlCTrDUcMANLDtIlax/I87oqsONOg5M2JS0jNSbZuAXDv7/YEGEtMKuIESBZh7pvVG8FV531/fyOZA iEA+POkE+QwVbUfGyeugR6IGvnt4yeOwkC3bUoATScsN98CIQDynBXC8YngDNwZ62QPX+ONpqCel6g8NO9VKC+ETaS87wIhAKRouxZL38PqfqV/WlZ5ZGd0Y S9gA360IK8zbOmHEkO/AiEAsES3iuvzQNYXFL3x9Tm2GzT1fkSx9wx+12BbJcVD7AECIQCD3Tv9S+AgRhQoNcuaSDNluVrL/B/wOmJRLqaOVJLQGg== publicKey:MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOvuGrxZ0Cj/ju27uWJ8VqDmY7956OGhVeefB0zw6F7OhBg9Bz+0c84RjzipqS0NQWwOb4kobfmg3W SV6ekr7TECAwEAAQ = = password: PNak4Yui0 ft6jsokbsgnpl + 2 + + L0np1o A033rdLhFw + HDRrCo9VkCuiiXviEMYwUgpHZUFxb2FpE0YmSguuRww = = then Yml add the following configuration: Spring: datasource: password: ${password} # Connection-properties: 'config.decrypt=true; config.decrypt.key=${publickey}' publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJvQUB7pExzbzTpaQCCY5qS+86MgYWvRpqPUCzjFwdMgrBjERE5X5oojSe48IGZ6UtCCeaI0PdhkFoNaJednaqMC AwEAAQ==Copy the code
The ConfigFilter will decrypt the password before setting it to the DataSource DataSource
2. Use Jasypt to encrypt packets
Jasypt is a Java library that allows developers to add basic encryption capabilities to their projects without having to have an in-depth understanding of how encryption works
How to use Jasypt in Spring Boot projects, please refer to Jasypt Github address
Introduction of depend on
<! -- Jasypt encryption tool, https://github.com/ulisesbocchio/jasypt-spring-boot --> <dependency> <groupId>com.github.ulisesbocchio</groupId> < artifactId > jasypt - spring - the boot - starter < / artifactId > < version > 3.0.3 < / version > < / dependency >Copy the code
Add annotations
Above to start the class add @ EnableEncryptableProperties annotations, environment is enabled for the Spring Jasypt encryption function, as follows:
@SpringBootApplication @EnableEncryptableProperties public class Application { public static void main(String[] args){ SpringApplication.run(Application.class, args); }}Copy the code
Obtain ciphertext
The jar package provided by Jasypt is used for encryption as follows:
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 {/** ** Generate a {@link PBEConfig} configuration object * <p> * note!! * to view Jasypt global default values in the configuration object {@ link JasyptEncryptorConfigurationProperties} * configuration consistent with the default values here, Otherwise, you need to define this configuration in application.yml (also via JVM parameters) * Note the password and algorithm configuration items, * * @param salt * @return SimpleStringPBEConfig Private static SimpleStringPBEConfig generatePBEConfig(String salt) { SimpleStringPBEConfig config = new SimpleStringPBEConfig(); // Set the salt value config.setpassword (salt); Config.setpoolsize ("1"); // Set the size of the encryption pool to be created. // Set the encryption algorithm, which must be supported by the JCE provider, default PBEWITHHMACSHA512ANDAES_256 config.setAlgorithm("PBEWithMD5AndDES"); / / set is applied to obtain the encryption key hash iterations config. SetKeyObtentionIterations (" 1000 "); // Set the name of the security provider to request the encryption algorithm config.setProviderName("SunJCE"); / / set the generator of the salt salt config. SetSaltGeneratorClassName (" org. Jasypt. Salt. RandomSaltGenerator "); / / IV generator set config. SetIvGeneratorClassName (" org. Jasypt. IV. RandomIvGenerator "); / / set the encoding of string output, support the base64 and hexadecimal config. SetStringOutputType (" base64 "); return config; } /** * Encryptor with {@link pooledPBeStringTor} ** @param salt * @param message encrypted content * @return encrypted content */ public static String encrypt(String salt, String message) { PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); SimpleStringPBEConfig pbeConfig = generatePBEConfig(salt); // Generate the 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()); // Encrypt 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(); // Set the encryptor.setConfig(generatePBEConfig(salt)); Return encryptor.decrypt(message); } public static void main(String[] args) {String salt = uid.randomuuid ().toString().replace("-", ""); // Encrypt (salt, "message"); }}Copy the code
How to use
Add Jasypt configuration and generated ciphertext directly to the application.yml configuration file
jasypt: encryptor: Password: salt# salt salt value, need to be consistent and salt used in encryption algorithm: PBEWithMD5AndDES # encryption algorithms, need and encryption algorithm used string - output - type: hexadecimal# cipher text format,, Spring: datasource: druid: username:root Password :ENC(cipherText)#Jasypt cipherText :ENC(cipherText)Copy the code
“Salt salt value can also be through the JVM parameter Settings, such as: – Djasypt. The encryptor. Password = salt”
After startup, Jasypt decrypts ENC(ciphertext) according to the configuration and then sets it to the Spring environment
The last
I have sorted it out: Mybatis common some knowledge points, Mybatis source analysis diagram, MyBtis interview analysis, Mybatis technical principle and combat PDF272 pages, Mybatis mind map (also Java core knowledge points, interview topics and 20 years of the latest Internet real questions, e-books, etc.) need friends can pay attention to the public number [procedures yuan small wan] can obtain.