一级缓存
jpa默认是有一级缓存的。
@Testpublic void testCache() {Customer customer = entityManager.find(Customer.class, 3);System.out.println(customer.getLastName());System.out.println("-------------");Customer customer1 = entityManager.find(Customer.class, 3);System.out.println(customer1.getLastName());}
二级缓存
@Testpublic void testCache1() {Customer customer = entityManager.find(Customer.class, 3); //这里一级缓存为什么没有生效呢????System.out.println(customer.getLastName());transaction.commit();entityManager.close();System.out.println("--------------");entityManager = entityManagerFactory.createEntityManager();transaction = entityManager.getTransaction();transaction.begin();Customer customer1 = entityManager.find(Customer.class, 3);System.out.println(customer1.getLastName());}
以上代码, 会发送二次sql语句,开启二级缓存,需要进行配置:
1.修改persistence.xml
<?xml version="1.0" encoding="UTF-8"?><persistence version="2.0"xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"><persistence-unit name="jpa-1" transaction-type="RESOURCE_LOCAL"><!--配置使用什么 ORM 产品来作为 JPA 的实现1. 实际上配置的是 javax.persistence.spi.PersistenceProvider 接口的实现类2. 若 JPA 项目中只有一个 JPA 的实现产品, 则也可以不配置该节点.--><provider>org.hibernate.ejb.HibernatePersistence</provider><!-- 添加持久化类 --><class>cn.carven.jpa.helloworld.Customer</class><class>cn.carven.jpa.helloworld.Order</class><class>cn.carven.jpa.helloworld.Department</class><class>cn.carven.jpa.helloworld.Manager</class><class>cn.carven.jpa.helloworld.Item</class><class>cn.carven.jpa.helloworld.Category</class><!--配置二级缓存的策略ALL:所有的实体类都被缓存NONE:所有的实体类都不被缓存.ENABLE_SELECTIVE:标识 @Cacheable(true) 注解的实体类将被缓存DISABLE_SELECTIVE:缓存除标识 @Cacheable(false) 以外的所有实体类UNSPECIFIED:默认值,JPA 产品默认值将被使用--><shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode><properties><!-- 连接数据库的基本信息 --><property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/><property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa"/><property name="javax.persistence.jdbc.user" value="root"/><property name="javax.persistence.jdbc.password" value="123456"/><!-- 配置 JPA 实现产品的基本属性. 配置 hibernate 的基本属性 --><property name="hibernate.format_sql" value="true"/><property name="hibernate.show_sql" value="true"/><property name="hibernate.hbm2ddl.auto" value="update"/><!-- 二级缓存相关 --><property name="hibernate.cache.use_second_level_cache" value="true"/><property name="hibernate.cache.region.factory_class"value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/><property name="hibernate.cache.use_query_cache" value="true"/></properties></persistence-unit></persistence>
2.在实体类中添加@Cacheable(true)注解
