1. Complemento de paginación PageHelper.
(1) El rol de pageHelper
Ayudarle a completar la función de paginación.
(2) Cómo usar:
1. Introduce el paquete jar de pageHelper
<!--引入pageHelperjar包-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.11</version>
</dependency>
2. Configure el interceptor de pageHelper en mybatis
Establecer en la pestaña de entornos
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
3 Use pageHelper -- en la clase de prueba
//设置分页属性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. Generador de código Mybatis --generador
(1) El papel de mybatis-generator
De acuerdo con la tabla, lo ayuda a generar clases de entidad y archivos de mapeo dao y xml. es simple CRUD
(2) Cómo usar
1. Introducir el paquete jar de mybatis-generator
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
2archivo de configuración del generador
<?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 &characterEncoding=UTF-8&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. Ejecute su propio archivo de configuración
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);
Hay muchos comentarios en inglés después de la ejecución, si no quiere escribir, bajo el contexto
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
3. caché mybatis
1. Qué es el caché --- El caché son datos temporales que existen == en la memoria ==.
2. Caché de nivel 1
Caché de nivel 1: caché basada en el nivel de SqlSession. La caché de primer nivel está habilitada de manera predeterminada y no se puede deshabilitar.
//一级缓存
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. Caché L2
Caché de segundo nivel: basado en el nivel de caché de SqlSessionFactory, puede compartir datos entre múltiples SqlSessions. Por defecto está apagado. Necesita ser encendido manualmente
1. Encienda el caché de segundo nivel --- en configuración
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
2. Use el caché de segundo nivel, debajo del archivo de mapeo
<cache/>
3. Implementar la interfaz de serialización de la entidad correspondiente
public class Student implements Serializable
4. Prueba el caché de segundo nivel
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);
}