[2020-02-16] integrate native Mybatis configuration as well as the SpringBoot

Foreword

    Today Sunday morning studied under Mybatis, afternoon cattle ready customer network test machine, computer-based test nothing to say, following on the record about learning Mybatis of today. The following mainly of two parts, the first part Mybatis native configuration, the second portion of the integration Mybatis with SpringBoot.

A, Mybatis native configuration

    pom.xml as long as you can rely on the introduction of mybatis and mysql because I used lombok, so dependent on the introduction of a multi-lombok of:

       <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>

    Xml and then configure the class shown below:

     In mybatis-config.xml, the source address data and configuration files mapper.xml:

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <environments default="development">
 7         <environment id="development">
 8             <transactionManager type="JDBC"/>
 9             <dataSource type="POOLED">
10                 <property name="driver" value="com.mysql.jdbc.Driver"/>
11                 <property name="url" value="jdbc:mysql://localhost:3306/my_project?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=Asia/Shanghai&amp;useSSL=false&amp;allowPublicKeyRetrieval=true"/>
12                 <property name="username" value="localuser"/>
13                 <property name="password" value="Jinger!"/>
14             </dataSource>
15         </environment>
16     </environments>
17     <mappers>
18         <mapper resource="mybatis/mapper/ManagerInfoMapper.xml"/>
19     </mappers>
20 </configuration>

 Finally, test access categories:

 1 package com;
 2 
 3 
 4 import com.mybatisDemo.entity.ManagerInfoEntityDO;
 5 import com.mybatisDemo.mapper.ManagerInfoMapper;
 6 import org.apache.ibatis.io.Resources;
 7 import org.apache.ibatis.session.SqlSession;
 8 import org.apache.ibatis.session.SqlSessionFactory; 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 10 11 import java.io.InputStream; 12 13 /** 14 * 通过原生的方式配置Mybatis 15 */ 16 public class MybatisDemo1 { 17 public static void main(String[] args) throws Exception { 18 String resource = "mybatis/mybatis-config.xml"; // 配置文件的相对地址 19 InputStream inputStream = Resources.getResourceAsStream(resource); 20 SqlSessionFactory sqlSessionFactory = 21 new SqlSessionFactoryBuilder().build(inputStream); 22 23 SqlSession sqlSession = sqlSessionFactory.openSession(); 24 ManagerInfoEntityDO entityDO = sqlSession.getMapper(ManagerInfoMapper.class).selectByPrimaryKey(5); 25 System.out.println("ManagerInfoEntityDO:" + entityDO); 26  } 27 }

    You can see the startup main method can successfully access the database. Thus, Mybatis is independent of the Spring or SpringBoot used, but usually we use are mostly based SpringBoot Mybatis should be used, so the following is a look at how to introduce Mybatis SpringBoot of.

Two, Mybatis integration with SpringBoot

    pom.xml added the following dependence, wherein the spring-boot-starter-web is introduced to the interface by calling the page, Druid is used to do the connection pool, the remaining two jar package is designed for the integration of both exist.

 1        <dependency>
 2             <groupId>org.springframework.boot</groupId>
 3             <artifactId>spring-boot-starter-web</artifactId>
 4         </dependency>
 5         <dependency>
 6             <groupId>org.mybatis.spring.boot</groupId>
 7             <artifactId>mybatis-spring-boot-starter</artifactId>
 8             <version>1.3.2</version>
 9         </dependency>
10         <dependency>
11             <groupId>org.mybatis</groupId>
12             <artifactId>mybatis-spring</artifactId>
13             <version>2.0.1</version>
14         </dependency>
15         <dependency>
16             <groupId>com.alibaba</groupId>
17             <artifactId>druid</artifactId>
18             <version>1.1.13</version>
19         </dependency>

    yml file to configure the location of mapper.xml:

server:
  port: 8090

mybatis:
  # Mapping file path
  mapper-locations: classpath:mybatis/mapper/*Mapper.xml

    Configuration database and scanning source AppConfig mapper interface:

 1 @Configuration
 2 @MapperScan("com.mybatisDemo.mapper")
 3 //@ComponentScan("com")
 4 public class AppConfig {
 5 
 6     private String userName = "localuser";
 7     private String password = "Jinger!";
 8     private String url = "jdbc:mysql://localhost:3306/my_project?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true";
 9     private String driverClassName = "com.mysql.jdbc.Driver";
10     
11     @Bean
12 is      @Primary
 13 is      public the DataSource the dataSource () {
 14          DruidDataSource the dataSource = new new DruidDataSource ();
 15          dataSource.setUrl (URL);
 16          dataSource.setUsername (the userName); // username 
. 17          dataSource.setPassword (password); // Password 
18 is          dataSource.setDriverClassName (driverClassName);
 . 19          dataSource.setInitialSize (. 5); // build the initialization of the number of physical connection 
20 is          dataSource.setMaxActive (50); // maximum number of connection pool 
21 is          dataSource.setMinIdle (. 1); //The minimum number of connection pool 
22 is          dataSource.setMaxWait (60000); // Get the maximum waiting time is connected, in milliseconds. 
23 is          dataSource.setTestWhileIdle ( to true );
 24          dataSource.setTestOnBorrow ( to false ); //
 25          dataSource.setTestOnReturn ( to false );
 26 is          dataSource.setPoolPreparedStatements ( to true ); // buffer cursor 
27          dataSource.setMaxPoolPreparedStatementPerConnectionSize (20 is); // cursor cache size 
28          dataSource.setTimeBetweenEvictionRunsMillis (60000); //Intervals the frequency of such detection, an idle connection is detected to be closed, milliseconds 
29          dataSource.setMinEvictableIdleTimeMillis (30000); // disposed a minimum connection time cell survival, milliseconds 
30          dataSource.setValidationQuery ( "the SELECT. 1 "); // for detecting connection is valid SQL 
31 is          dataSource.setTestOnBorrow ( to false ); // perform validationQuery connection is valid application for detecting connection 
32          dataSource.setTestWhileIdle ( to true ); // recommended configuration to true, does not affect the performance of and ensure security. 
33 is          dataSource.setPoolPreparedStatements ( to false ); // if the cache preparedStatement, i.e. PSCache 
34 is          return the dataSource;
 35     }
36 
37 }

    Call mapper interface MyService in:   

1 @Service
2 public class MyService {
3     @Autowired
4     private ManagerInfoMapper managerInfoMapper;
5 
6     public ManagerInfoEntityDO selectByPrimaryKey(Integer id) {
7         return managerInfoMapper.selectByPrimaryKey(id);
8     }
9 }

 

    The last test of the main categories:

 1 **
 2  * SpringBoot与Mybatis整合
 3  */
 4 @SpringBootApplication
 5 @Controller
 6 public class MybatisDemo3 {
 7 
 8     @Autowired
 9     private MyService managerService;
10 
11     public static void main(String[] args) {
12         SpringApplication.run(MybatisDemo3.class, args);
13     }
14 
15     @RequestMapping("/test")
16     @ResponseBody
17     public ManagerInfoEntityDO myTest () {
18         ManagerInfoEntityDO entityDO = managerService.selectByPrimaryKey(5);
19         System.out.println(entityDO);
20         return entityDO;
21     }
22 }

    After starting the class, visit localhost: 8090 / test is able to properly access the database.

summary

    It can be seen after consolidation and SpringBoot, Mybatis simply configure or two can use, extremely convenient. Today also done some research principles Mybatis and SpringBoot integration, but not completely clear, for the time being do not do a detailed record, only posted a flow sketch, dig a hole.

 

Guess you like

Origin www.cnblogs.com/zzq6032010/p/12319455.html