In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, I would like to share with you how SpringBoot integrates Mybatis and tests related knowledge points, the content is detailed, the logic is clear, I believe most people still know too much about this knowledge, so share this article for your reference, I hope you can get something after reading this article, let's take a look at it.
First of all, let's create a new project. We need to select the following dependencies:
1. SpringBoot Link druid connection Pool
1. Add the druid connection pool scenario initiator in the pom file, as shown below:
Com.alibaba druid-spring-boot-starter 1.2.3
2. Add the following configuration to the global configuration class:
Spring: # application: # name: dev-manager datasource: # configuration data source type type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot_mybatis?useUnicode=true&characterEncoding=UTF-8 username: root password: root # initialization, minimum Maximum number of connections initialSize: 3 minidle: 3 maxActive: 18 # get the timeout of database connection waiting maxWait: 60000 # configure how often to detect and detect the idle connection units that need to be closed millisecond timeBetweenEvictionRunsMillis: 60000 validationQuery: SELECT 1 FROM dual # configure the filters intercepted by monitoring statistics The sql of the monitoring interface cannot be counted # filters: stat,wall,log4j # run the sql script schema: classpath:sql/schema.sql initialization-mode: always druid: stat-view-servlet: enabled: true during initialization
3. At this time, the data link of druid is already linked. Next, we can configure some druid monitoring. First, we can analyze that the DruidStatViewServletConfiguration introduced in the automatic configuration class is monitored, and a monitoring interface can be generated.
@ Configuration@ConditionalOnClass ({DruidDataSource.class}) @ AutoConfigureBefore ({DataSourceAutoConfiguration.class}) @ EnableConfigurationProperties ({DruidStatProperties.class, DataSourceProperties.class}) / / DruidStatViewServletConfiguration is the class @ Import ({DruidSpringAopConfiguration.class, DruidStatViewServletConfiguration.class, DruidWebStatFilterConfiguration.class, DruidFilterConfiguration.class}) public class DruidDataSourceAutoConfigure {}
4. When we click to enter the DruidStatViewServletConfiguration class, we will find that when we do not configure the spring.datasource.druid.stat-view-servlet.enabled configuration in the global configuration file, the class will not take effect and the monitoring interface will not be able to rise. The code is as follows:
@ ConditionalOnWebApplication@ConditionalOnProperty (name = {"spring.datasource.druid.stat-view-servlet.enabled"}, havingValue = "true") public class DruidStatViewServletConfiguration {}
5. Let's not configure the above attributes in the global configuration. If we enter the address http://localhost:8080/druid/login.html, it will not be opened, as shown below:
6. After we have configured this configuration in the global configuration file, we will open the monitored website page, as shown below:
Spring: datasource: druid: stat-view-servlet: enabled: true
7. According to the following code of the DruidStatViewServletConfiguration class, we can similarly add some other configurations, such as login name and password, as follows:
Application.yml configuration
Druid: stat-view-servlet: enabled: true login-username: root login-password: 1232, SpringBoot integrates Mybatis2.1, introduces Mybatis-generator
1. Introduce the mybatis-generator plug-in into the pom file. The code is as follows:
Org.mybatis.generator mybatis-generator-maven-plugin 1.3.2 ${project.basedir} / src/main/resources/generatorConfig.xml true true mysql mysql-connector-java 8.0.22
2. Add the generatorConfig.xml file introduced above. The code example is as follows:
3. Find the plug-in in maven and double-click to run it
2.2.Integration and testing of mybatis
1. Introduce the dependency of mybatis and mysql in the pom file. The code is as follows:
Org.mybatis.spring.boot mybatis-spring-boot-starter 2.2.0 mysql mysql-connector-java runtime
2. Configure the path of mapper-location in the global configuration file, and specify where the mapper.xml file is located.
# set mapper-locationmybatis: mapper-locations: classpath:cool/ale/mapper/*Mapper.xml of mybatis
3. Specify the path to the mapper interface where the SpringBoot launches the class, as shown below:
@ MapperScan ("cool.ale.mapper") public class SpringbootMybatisApplication {public static void main (String [] args) {SpringApplication.run (SpringbootMybatisApplication.class, args);}}
4. Write a controller to test the CRUD code you just generated:
Package cool.ale.controller;import cool.ale.mapper.EmpMapper;import cool.ale.pojo.Emp;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController@RequestMapping ("/ emp") public class EmpController {@ Autowired private EmpMapper empMapper; @ RequestMapping ("/ all") public List selectAll () {return empMapper.selectAll ();}
5. The successful screenshot is as follows:
3. Other 3.1Custom druid link pool
1. Add dependencies to the pom file:
Com.alibaba druid 1.2.3
2. Configuration in global configuration:
Spring: # application: # name: dev-manager datasource: # configuration data source type type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot_mybatis?useUnicode=true&characterEncoding=UTF-8 username: root password: root # initialization, minimum Maximum number of connections initialSize: 3 minidle: 3 maxActive: 18 # get the timeout of database connection waiting maxWait: 60000 # configure how often to detect and detect the idle connection units that need to be closed millisecond timeBetweenEvictionRunsMillis: 60000 validationQuery: SELECT 1 FROM dual # configure the filters intercepted by monitoring statistics The sql of the monitoring interface cannot be counted # filters: stat,wall,log4j # run the sql script schema: classpath:sql/schema.sql initialization-mode: always during initialization
3. Write the configuration class, which is similar to the method we just wrote in the jar package. The code is as follows:
Package cool.ale.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.autoconfigure.condition.ConditionalOnProperty;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 javax.sql.DataSource @ Configuration// this class takes effect only when our global configuration file is configured with the spring.datasource.type attribute. @ ConditionalOnProperty ("spring.datasource.type") public class DruidConfiguration {@ Bean / / binds all configurations starting with spring.datasource from application.yml to DataSource @ ConfigurationProperties ("spring.datasource") public DataSource dataSource () {return new DruidDataSource () } / * / the second method public DataSource dataSource (DataSourceProperties properties) {/ / dynamically create a DataSource return properties.initializeDataSourceBuilder (). Build () according to the configuration;} * / * servlet * / public ServletRegistrationBean statViewServlet () {ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean (); servletRegistrationBean.setServlet (new StatViewServlet ()) / / after setting this property, we can access a druid monitor station through druid address / / for example: http://localhost:8080/druid/login.html servletRegistrationBean.addUrlMappings ("/ druid/*"); / / add IP whitelist servletRegistrationBean.addInitParameter ("allow", "127.0.0.1") / / add IP blacklist. When the whitelist and blacklist are duplicated, the blacklist has a higher priority servletRegistrationBean.addInitParameter ("deny", "127.0.0.1"); / / add console management user servletRegistrationBean.addInitParameter ("loginUsername", "admin"); servletRegistrationBean.addInitParameter ("loginPassword", "123456") / / whether the data servletRegistrationBean.addInitParameter ("resetEnable", "false") can be reset; return servletRegistrationBean; * configure service filter: monitor which accesses * * @ return return filter configuration object public FilterRegistrationBean statFilter () {FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean (new WebStatFilter ()) / / add filter rules, all requests will be blocked by filterRegistrationBean.addUrlPatterns ("/ *"); / / ignore filter format filterRegistrationBean.addInitParameter ("exclusions", "* .js,*.gif,*.jpg,/druid/*"); return filterRegistrationBean;} 3.2, other Mybatis configuration of SpringBoot @ Bean@ConditionalOnMissingBeanpublic SqlSessionFactory sqlSessionFactory (DataSource dataSource) throws Exception {SqlSessionFactoryBean factory = new SqlSessionFactoryBean () Factory.setDataSource (dataSource); factory.setVfs (SpringBootVFS.class); / / set Mybatis's global configuration file if (StringUtils.hasText (this.properties.getConfigLocation () {factory.setConfigLocation (this.resourceLoader.getResource (this.properties.getConfigLocation () } / / there is another customization method / / there is some implementation of setting for mybatis global configuration files this.applyConfiguration (factory); if (this.properties.getConfigurationProperties ()! = null) {factory.setConfigurationProperties (this.properties.getConfigurationProperties ()) / / Mybatis's plug-in interceptor, / / We only need an interceptor that implements an Interceptor interface to be injected into the IOC container to work if (! ObjectUtils.isEmpty (this.interceptors)) {factory.setPlugins (this.interceptors); / / set database vendor ID if (this.databaseIdProvider! = null) {factory.setDatabaseIdProvider (this.databaseIdProvider) / / go to application.yml to find typeAliasesPackage attribute, set alias to use if (StringUtils.hasLength (this.properties.getTypeAliasesPackage () {factory.setTypeAliasesPackage (this.properties.getTypeAliasesPackage ()); / / set alias to subclass according to parent class / / go to application.yml to find aliasesSuperType attribute if (this.properties.getTypeAliasesSuperType ()! = null) {factory.setTypeAliasesSuperType (this.properties.getTypeAliasesSuperType () / / set the type handler if (StringUtils.hasLength (this.properties.getTypeHandlersPackage () {factory.setTypeHandlersPackage (this.properties.getTypeHandlersPackage ()) through the package; / / set the type processor if (! ObjectUtils.isEmpty (this.typeHandlers)) {factory.setTypeHandlers (this.typeHandlers) through the class / / set mapper-location if (! ObjectUtils.isEmpty (this.properties.resolveMapperLocations () {factory.setMapperLocations (this.properties.resolveMapperLocations ()); Set factoryPropertyNames = (Set) Stream.of ((new BeanWrapperImpl (SqlSessionFactoryBean.class)) .getPropertyDescriptors ()) .map (FeatureDescriptor::getName) .requests (Collectors.toSet ()); Class
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.