Mybatis a source of learning

  1. Create rely Mybatis of:

<?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>org.example</groupId>
    <artifactId>MyBatisDemo</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>
        <!--添加Spring依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>
        <!--添加Spring-JDBC依赖 -->
        <!--提供了数据库连接池-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>


        <!--添加Mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <!--添加Mybatis-Spring依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>Spring-MyBatis </ the artifactId> 
        <-! added MySQL dependent ->
            <version>1.3.2</version>
        </ dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
        <!--添加日志依赖-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.8.0-beta4</version>
        </dependency>
        <!--添加log4j依赖 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>
</project>

  2. Create the configuration class:

 1 package com.wk.app;
 2 
 3 import org.apache.ibatis.logging.log4j.Log4jImpl;
 4 import org.apache.ibatis.session.SqlSessionFactory;
 5 import org.mybatis.spring.SqlSessionFactoryBean;
 6 import org.mybatis.spring.annotation.MapperScan;
 7 import org.springframework.context.annotation.Bean;
 8 import org.springframework.context.annotation.ComponentScan;
 9 import org.springframework.context.annotation.Configuration;
10 import org.springframework.jdbc.datasource.DriverManagerDataSource;
. 11  
12 is  Import the javax.sql.DataSource;
 13 is  
14  / ** 
15  * configuration class
 16   * / 
. 17  @Configuration
 18 is @ComponentScan ( "com.wk" )
 . 19 @MapperScan ( "com.wk.dao") // role scanning added @Mapper annotation class 
20 is  public  class appconfig {
 21 is  
22 is      / ** 
23 is       * create a data source
 24       * @return 
25       * / 
26 is      @Bean
 27      public the dataSource the dataSource () {
 28           the DriverManagerDataSource DriverManagerDataSource =new new the DriverManagerDataSource ();
 29         driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
30         driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/seckill?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC");
31         driverManagerDataSource.setUsername("root");
32         driverManagerDataSource.setPassword("root");
33         return driverManagerDataSource;
40Exception
@throws     *39@return     *38 is     * Create instance SqlSessionFactoryBean
37/ **3635    }
34  
     
  
       */
41     @Bean
42     public SqlSessionFactory sqlSessionFactory() throws Exception {
43         SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
44         factoryBean.setDataSource(dataSource());
45         //通过编码方式设置mybatis的配置
46         /*org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
47         configuration.setLogImpl(Log4jImpl.class);
48         factoryBean.setConfiguration(configuration);*/
49         return factoryBean.getObject();
50     }
51 }

  3. Create Mapper interface and implement the query:

 1 package com.wk.dao;
 2 
 3 import com.wk.entity.Seckill;
 4 import org.apache.ibatis.annotations.Param;
 5 import org.apache.ibatis.annotations.Select;
 6 
 7 import java.math.BigInteger;
 8 
 9 public interface SeckillMapper {
10 
11     @Select("SELECT * FROM seckill WHERE seckill_id = #{seckillId}")
12     Seckill querySeckillById(@Param("seckillId") BigInteger seckillId);
13 }

  4. Create a service dependent on injected Mapper:

 1 @Service("seckillService")
 2 public class SeckillServiceImpl implements SeckillService {
 3     //注入依赖
 4     @Autowired
 5     SeckillMapper seckillMapper;
 6 
 7     public Seckill getSeckillById(BigInteger seckillId) {
 8         return seckillMapper.querySeckillById(seckillId);
 9     }
10 }

  5. Create a test class:

 1 /**
 2  * 测试类
 3  */
 4 public class Test {
 5     public static void main(String[] args) {
 6         //org.apache.ibatis.logging.LogFactory.useLog4JLogging();
 7         ApplicationContext context = new AnnotationConfigApplicationContext(APPConfig.class);
 8         SeckillService service = (SeckillService) context.getBean("seckillService");
 9         System.out.println(service.getSeckillById(new BigInteger("1000")));
10     }
11 }

  Here, a complete mybatis function is complete.

  mybatis implementation of sql statement printed journal (there are two):

  The first:

    1. Create a log4j.properties, reference mybatis official website

1 # Global logging configuration
2 log4j.rootLogger=DEBUG,stdout
3 # MyBatis logging configuration...设置sql语句的打印作用域
4 #log4j.logger.org.mybatis.example.BlogMapper=TRACE
5 log4j.logger.com.wk.dao.SeckillMapper.querySeckillById=TRACE
6 # Console output...
7 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
8 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
9 log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

    2. The introduction of log4j dependency:

<!-- 引入log4j的依赖-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

  3. Add the test method of performing org.apache.ibatis.logging.LogFactory.useLog4JLogging class () ;:

 1 /**
 2  * 测试类
 3  */
 4 public class Test {
 5     public static void main(String[] args) {
 6         //日志打印sql执行语句
 7         org.apache.ibatis.logging.LogFactory.useLog4JLogging();
 8         ApplicationContext context = new AnnotationConfigApplicationContext(APPConfig.class);
 9         SeckillService service = (SeckillService) context.getBean("seckillService");
10         System.out.println(service.getSeckillById(new BigInteger("1000")));
11     }
12 }

  The second:

    To control the encoding program by way of adding the log print function

    Configuration using class setLogImpl (Log4jImpl.class); function realization method.

1  / * 
2  * configuration class
 . 3   * / 
. 4  @Configuration
 . 5 @ComponentScan ( "com.wk" )
 . 6 @MapperScan ( "com.wk.dao") // function is added @Mapper scanning annotated classes 
. 7  public  class appconfig {
 . 8  
. 9      / ** 
10       * create a data source
 . 11       * @return 
12 is       * / 
13 is      @Bean
 14      public the dataSource the dataSource () {
 15          the DriverManagerDataSource DriverManagerDataSource = new new the DriverManagerDataSource ();
 16         driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
17         driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/seckill?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC");
18         driverManagerDataSource.setUsername("root");
19         driverManagerDataSource.setPassword("root");
20         return driverManagerDataSource;
27Exception
@throws     *26 is@return     *25     * Create instance SqlSessionFactoryBean
24/ **23 is22 is    }
21  
     
  
       */
28     @Bean
29     public SqlSessionFactory sqlSessionFactory() throws Exception {
30         SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
31         factoryBean.setDataSource(dataSource());
32         //通过编码方式设置mybatis的配置
33         org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
34         configuration.setLogImpl(Log4jImpl.class);
35         factoryBean.setConfiguration(configuration);
36         return factoryBean.getObject();
37     }
38 }

 

After Mybatis that spring to integrate, what is the reason a cache miss is?

  Because after mybatis integration and spring, spring will be in session management mybatis database queries, after each finished query, spring will close the session, even if it is the same query, mybatis Always use the new session to establish a connection query, after completion of inquiry, the session was closed container spring, resulting in a cache mybatis failure.

Mybatis secondary cache disadvantages:

  Mybatis secondary cache is based namespace, that is, only methods in a Mapper class, if a query method and an update method is not carried out under the same Mapper class, mybatis secondary cache will be ignored data after the update, still use the cache before, resulting in data errors.

Guess you like

Origin www.cnblogs.com/wk-missQ1/p/12628888.html