Catalog
Configure data source related parameters
Query data (persistent interfaces and mapper files)
Preface
This section focuses on boot integrating mybatis and thymeleaf, then making a simple alignment between the front and back ends.Pave the way for subsequent full-text log processing and full-text exception handling
Integrate mybatis
Import Dependency
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
Configure data source related parameters
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root
Custom connection pool
Whether mybatis, jpa, or JdbcTemplate is used, the connection pool configuration used by default is tomcat.jdbc.pool
You can go into the org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration class to see how data sources are configured.Here we use the druid connection pool
Import Dependency
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.25</version> </dependency>
#Do not specify that the default connection pool for spring.datasource.type is tomcat.jdbc.pool spring.datasource.type=com.alibaba.druid.pool.DruidDataSource # Data Source Other Configurations spring.datasource.initialSize:5 spring.datasource.minIdle:5 spring.datasource.maxActive:20 spring.datasource.maxWait:60000 spring.datasource.timeBetweenEvictionRunsMillis:60000 spring.datasource.minEvictableIdleTimeMillis:300000 spring.datasource.validationQuery:SELECT 1 FROM DUAL spring.datasource.testWhileIdle:true spring.datasource.testOnBorrow:false spring.datasource.testOnReturn:false spring.datasource.poolPreparedStatements:true # Configure filters intercepted by monitoring statistics, sql cannot be counted after removal,'wall'for firewall spring.datasource.filters: stat,wall,log4j spring.datasource.maxPoolPreparedStatementPerConnectionSize: 20 spring.datasource.useGlobalDataSourceStat: true spring.datasource.connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
We can see the parameters provided by the connection pool configuration class provided by boot
The following property configurations are not available
spring.datasource.initialSize:5 spring.datasource.minIdle:5 spring.datasource.maxActive:20 spring.datasource.maxWait:60000 spring.datasource.timeBetweenEvictionRunsMillis:60000 spring.datasource.minEvictableIdleTimeMillis:300000 spring.datasource.validationQuery:SELECT 1 FROM DUAL spring.datasource.testWhileIdle:true spring.datasource.testOnBorrow:false spring.datasource.testOnReturn:false spring.datasource.poolPreparedStatements:true
Since there is no configuration for druid-related parameters, we will manually configure a connection pool class with the following code
package com.javayihao.myweb.config; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * @Author xiaoyuan * @Des * @Date create in 14:232019/6/6 * @ */ //Data Source Configuration @Configuration public class DruidConfig { //Configure everything prefixed with spring.datasource @ConfigurationProperties(prefix = "spring.datasource") //Customize a data source and inject it into the container @Bean public DataSource druid() { return new DruidDataSource(); } //druid monitoring can also be configured here //1. Configure a Servlet to manage the background @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); Map<String,String> initParams = new HashMap<>(); //Configure what can be viewed in StatViewServlet initParams.put("loginUsername","lphluck"); initParams.put("loginPassword","13578lph"); initParams.put("allow","");//The default is to allow all access initParams.put("deny","192.168.15.21");//access denied bean.setInitParameters(initParams); return bean; } //2. Configure a filter for web Monitoring @Bean public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); Map<String,String> initParams = new HashMap<>(); //No Interception initParams.put("exclusions","*.js,*.css,/druid/*"); bean.setInitParameters(initParams); //Intercept all requests bean.setUrlPatterns(Arrays.asList("/*")); return bean; } }
Start the project, we visit the data source to view http://localhost:8080/druid/login.html Use our configured account and password to enter the view
It is easy to see how sql is running
Query data (persistent interfaces and mapper files)
Here, for example, a taxonomy query for a specified taxonomy, the persistence interface and mapper file are as follows
@Mapper @Repository public interface TypeMapper { Type selectByPrimaryKey(Integer id); }
<?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="com.javayihao.top.blog.dao.TypeMapper"> <resultMap id="BaseResultMap" type="com.javayihao.top.blog.pojo.Type"> <id column="id" jdbcType="INTEGER" property="id" /> <result column="name" jdbcType="VARCHAR" property="name" /> </resultMap> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select id, name from type where id = #{id,jdbcType=INTEGER} </select> </mapper>
test
@RunWith(SpringRunner.class) @SpringBootTest public class TypeDaoTest { @Autowired private TypeMapper typeMapper; @Test public void getTypeById() { Integer id = 1; Type type = typeMapper.selectByPrimaryKey(id); System.out.println(type); } }
Display results
Type{id=1, name='java base'}
Integration Successful
Transactions in boot project
Program Entry Add Comment@EnableTransactionManagement
@SpringBootApplication @EnableTransactionManagement public class BlogApplication { public static void main(String[] args) { SpringApplication.run(BlogApplication.class, args); } }
Annotate the class or method where the transaction exists
@Transactional(rollbackFor=Exception.class,propagation = Propagation.NOT_SUPPORTED)
This kind of transaction management above requires an add transaction annotation, which is handled uniformly in ssm projects by xml configuration
<!-- Configure Transaction Manager --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- Configure transaction notifications --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED" read-only="false"/> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!-- To configure aop --> <aop:config> <aop:pointcut expression="execution(* com.javayihao.blog.service.impl.*.*(..))" id="pt1"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/> </aop:config>
In boot, xml configuration processing is not recommended but handled by each configuration class, where we customize a global transaction configuration class
First import dependencies that support facets
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
Configuration Class
@Aspect @Configuration public class TranactionConfig { //Specify Transaction Scope private static final String AOP_POINTCUT_EXCEPTION = "execution(* com.javayihao.top.blog.service.*.*(..)"; @Autowired private PlatformTransactionManager transactionManager; @Bean public TransactionInterceptor txAdvice() { //Set the propagation mechanism behavior for transactions, such as when to roll back isolation levels DefaultTransactionAttribute transactionAttribute = new DefaultTransactionAttribute(); transactionAttribute.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); transactionAttribute.rollbackOn(new Throwable());//Roll back when an exception occurs transactionAttribute.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);//Execute the last transaction after it has been executed // Read-only transaction DefaultTransactionAttribute transactionAttribute_readonly = new DefaultTransactionAttribute(); transactionAttribute_readonly.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); transactionAttribute_readonly.setReadOnly(true); NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource(); //General Formulation Method source.addTransactionalMethod("add*",transactionAttribute); source.addTransactionalMethod("insert*",transactionAttribute); source.addTransactionalMethod("save*",transactionAttribute); source.addTransactionalMethod("delete*",transactionAttribute); source.addTransactionalMethod("update*",transactionAttribute); source.addTransactionalMethod("exe*",transactionAttribute); source.addTransactionalMethod("set*",transactionAttribute); source.addTransactionalMethod("get*",transactionAttribute); source.addTransactionalMethod("query*",transactionAttribute); source.addTransactionalMethod("find*",transactionAttribute); source.addTransactionalMethod("list*",transactionAttribute); source.addTransactionalMethod("count*",transactionAttribute); source.addTransactionalMethod("is*",transactionAttribute); return new TransactionInterceptor(transactionManager,source); } //Open Transaction @Bean public Advisor txtAdviceAdvisor(){ AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression(AOP_POINTCUT_EXCEPTION); return new DefaultPointcutAdvisor(pointcut,txAdvice()); } }
Here the global transaction is almost complete, and the last point to check is that the data engine for the mysql database is innoDB
Integrate mybatis with global transaction here, get code please pay attention to public number java 1
Subsequently, it mainly introduces and develops how to do global log processing in boot project.
Get Code Focus on Public Number java 1 and work on the latest java real-world project!!!