plugin de paginação mybatis cache mybatis-generator

1. Plugin de paginação PageHelper.

(1) O papel do pageHelper

Ajudá-lo a completar a função de paginação

(2) Como usar:

1. Apresente o pacote jar do pageHelper

     <!--引入pageHelperjar包-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.11</version>
        </dependency>

        2. Defina o interceptor do pageHelper no mybatis

Defina na guia ambientes

 <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

        3 Use pageHelper -- na classe de teste

      //设置分页属性pageNum:显示第几页  PageSize:每页显示的条数
        PageHelper.startPage(2,5);
        List<User> list = userDao.findAll();
        //把查询的结果封装到PageInfo类中。
        PageInfo<User> pageInfo=new PageInfo<User>(list);
        System.out.println("总条数:"+pageInfo.getTotal());
        System.out.println("总页数:"+pageInfo.getPages());
        System.out.println("当前页码对应的数据:"+pageInfo.getList());

2. Gerador de código Mybatis --generator

        (1) O papel do gerador mybatis

De acordo com a tabela ajudá-lo a gerar classes de entidade e arquivos de mapeamento dao e xml. é simples CRUD

         (2) Como usar

        1. Apresente o pacote jar do mybatis-generator

       <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.4.0</version>
        </dependency>

        2arquivo de configuração do gerador

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
  <classPathEntry location="自己的MySQL的路径" />

  <context id="DB2Tables" targetRuntime="MyBatis3">
<!--根据自己的账号和密码修改-->
    <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/five?serverTimezone=Asia/Shanghai &amp;characterEncoding=UTF-8&amp;nullCatalogMeansCurrent=true"
        userId="db2admin"
        password="db2admin">
    </jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>
 <!--java 实体类的位置-->
    <javaModelGenerator targetPackage="要创建的实体类的包名" targetProject="实体类的路径">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>
<!--映射文件的位置-->
    <sqlMapGenerator targetPackage="映射文件的包名"  targetProject="映射文件的路径">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>
<!--dao包数据访问层-->
    <javaClientGenerator type="XMLMAPPER" targetPackage="要创建的dao的包名"  targetProject="bao的路径">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>
<!--数据库和实体的映射关系-->
    <table schema="数据库的名字" tableName="表名" domainObjectName="实体类的名字" 
enableUpdateByExample="false" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false">
     </table>

  </context>
</generatorConfiguration>

        3. Execute seu próprio arquivo de configuração

   List<String> warnings = new ArrayList<String>();
   boolean overwrite = true;
   File configFile = new File("generatorConfig.xml");
   ConfigurationParser cp = new ConfigurationParser(warnings);
   Configuration config = cp.parseConfiguration(configFile);
   DefaultShellCallback callback = new DefaultShellCallback(overwrite);
   MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
   myBatisGenerator.generate(null);

Há muitos comentários em inglês após a execução, se você não quiser escrever -- sob o contexto

 <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

3. cache mybatis

        1. O que é Cache --- Cache são dados temporários que existem == na memória ==.

        2. Cache de nível 1

        Cache de nível 1 - Cache baseado no nível SqlSession. O cache de primeiro nível é habilitado por padrão e não pode ser desabilitado.

        

        //一级缓存
        Reader reader = Resources.getResourceAsReader("conf.xml");
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
        SqlSession session= factory.openSession();
        StudentMapper mapper = session.getMapper(StudentMapper.class);
        //一级缓存:如果第一次执行的时候,在缓存中可以找到,就不会去数据库中查找,如果在缓存中找不到,会去数据库中查找
        Student student = mapper.selectByPrimaryKey(59);
        System.out.println(student);
        Student student1 = mapper.selectByPrimaryKey(59);

 @Test
    public void Test02()throws Exception{
        //一级缓存 在不同的SQLsession中 查询的内容一样
        Reader reader = Resources.getResourceAsReader("conf.xml");
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
        SqlSession session= factory.openSession();
        StudentMapper mapper = session.getMapper(StudentMapper.class);
        Student student = mapper.selectByPrimaryKey(59);
        System.out.println(student);
        //开启新的SQlSession 
        SqlSession session1= factory.openSession();
        StudentMapper mapper1 = session1.getMapper(StudentMapper.class);
        Student student1 = mapper1.selectByPrimaryKey(59);
        System.out.println(student1);
    }

         3. Cache L2

Cache de segundo nível - com base no cache de nível SqlSessionFactory, ele pode compartilhar dados entre várias SqlSessions. Por padrão está desligado. Precisa ser ativado manualmente

                1. Ative o cache de segundo nível --- na configuração

<settings>
    <setting name="cacheEnabled" value="true"/>
</settings>

                2. Use o cache de segundo nível -- sob o arquivo de mapeamento

  <cache/>

                3. Implemente a interface de serialização da entidade correspondente

public class Student implements Serializable

                4. Teste o cache de segundo nível

 public void Test03()throws Exception{
        //二级缓存
        Reader reader = Resources.getResourceAsReader("conf.xml");
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
        SqlSession session= factory.openSession();
        StudentMapper mapper = session.getMapper(StudentMapper.class);
        Student student = mapper.selectByPrimaryKey(59);
        System.out.println(student);
        session.close();
        //开启新的SQlSession
        SqlSession session1= factory.openSession();
        StudentMapper mapper1 = session1.getMapper(StudentMapper.class);
        Student student1 = mapper1.selectByPrimaryKey(59);
        System.out.println(student1);
    }

Acho que você gosta

Origin blog.csdn.net/ne_123456/article/details/125153906
Recomendado
Clasificación