ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【SpringData&JPA从入门到精通】04-缓存与 JPQL

2022-05-19 23:35:22  阅读:258  来源: 互联网

标签:Customer customer0 SpringData 04 JPA _. where id select


笔记来源:尚硅谷jpa开发教程全套完整版(初学者零基础入门)

目录

缓存与 JPQL

1、缓存

1.1、一级缓存

测试方法 1

@Test
public void testSecondaryCache(){
    Customer customer1 = entityManager.find(Customer.class, 1);
    Customer customer2 = entityManager.find(Customer.class, 1);
}

日志信息

Hibernate: 
    select
        customer0_.id as id1_2_0_,
        customer0_.age as age2_2_0_,
        customer0_.birthDay as birthDay3_2_0_,
        customer0_.createTime as createTi4_2_0_,
        customer0_.email as email5_2_0_,
        customer0_.LAST_NAME as LAST_NAM6_2_0_ 
    from
        JPA_CUSTOMERS customer0_ 
    where
        customer0_.id=?

由于 JPA 的一级缓存,所以实际上只发送了一条 SQL

测试方法 2

@Test
public void testSecondaryCache(){
    Customer customer1 = entityManager.find(Customer.class, 1);

    entityTransaction.commit();
    entityManager.close();

    entityManager = entityManagerFactory.createEntityManager();
    entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();

    Customer customer2 = entityManager.find(Customer.class, 1);
}

日志信息

Hibernate: 
    select
        customer0_.id as id1_2_0_,
        customer0_.age as age2_2_0_,
        customer0_.birthDay as birthDay3_2_0_,
        customer0_.createTime as createTi4_2_0_,
        customer0_.email as email5_2_0_,
        customer0_.LAST_NAME as LAST_NAM6_2_0_ 
    from
        JPA_CUSTOMERS customer0_ 
    where
        customer0_.id=?
Hibernate: 
    select
        customer0_.id as id1_2_0_,
        customer0_.age as age2_2_0_,
        customer0_.birthDay as birthDay3_2_0_,
        customer0_.createTime as createTi4_2_0_,
        customer0_.email as email5_2_0_,
        customer0_.LAST_NAME as LAST_NAM6_2_0_ 
    from
        JPA_CUSTOMERS customer0_ 
    where
        customer0_.id=?

这次由于 entityManager 是重新获取的,一级缓存中的内容已经被清理掉了,所以发送了两条 SQL

二级缓存 的意义就在于可以跨 JPA 中的 EntityManager,是上述方法可以是发送一条 SQL

1.2、二级缓存

在使用二级缓存前需要做以下准备工作

pom.xml 中添加 二级缓存 相关依赖

<!-- 二级缓存相关依赖 -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache-core</artifactId>
    <version>2.4.3</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-ehcache</artifactId>
    <version>4.2.4.Final</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.6.1</version>
</dependency>

persistence.xml 中添加 二级缓存 相关配置

<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
    <persistence-unit name="jpa-1" transaction-type="RESOURCE_LOCAL">
        <!--略...-->
        <!--配置二级缓存策略
            ALL:所有的实体类都被缓存
            NONE:所有的实体类都不被缓存
            ENABLE_SELECTIVE:标识 @Cacheable(true) 注解的实体类将被缓存
            DISABLE_SELECTIVE:除标识 @Cacheable(false) 注解以外的所有实体类都将被缓存
            UNSPECIFIED:默认值,JPA 产品默认值将被使用
        -->
        <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
        <properties>
            <!--略...-->
            <!--二级缓存相关-->
            <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>

Customer.java 中添加 二级缓存 相关注解

@Cacheable(value = true)
@Entity
@Table(name = "JPA_CUSTOMERS")
public class Customer {
    // ...
}

再次运行上述代码,查看日志信息

Hibernate: 
    select
        customer0_.id as id1_2_0_,
        customer0_.age as age2_2_0_,
        customer0_.birthDay as birthDay3_2_0_,
        customer0_.createTime as createTi4_2_0_,
        customer0_.email as email5_2_0_,
        customer0_.LAST_NAME as LAST_NAM6_2_0_ 
    from
        JPA_CUSTOMERS customer0_ 
    where
        customer0_.id=?

2、JPQL

2.1、JPQL 语言

  • JPQL 语言,即 Java Persistence Query language 的简称
  • JPQL 是一种和 SQL 非常类似的中间性和对象化查询语言,它最终会被编译成针对不同底层数据库的 SQL 查询,从而屏蔽不同数据库的差异
  • JPQL 语言的语句可以是 select 语句、update 语句或 delete 语句,它们都通过 Query 接口封装执行

2.2、Query 接口

Query 接口封装了执行数据库查询的相关方法调用 EntityManager 的 createQuerycreateNamedQuerycreateNativeQuery 方法可以获得查询对象,进而可调用 Query 接口的相关方法来执行查询操作

Query 接口的主要方法

  • int executeUpdate() 用于执行 update 或 delete 语句
  • List getResultList() 用于执行 select 语句并返回结果集实体列表
  • Object getsingleResult() 用于执行只返回单个结果实体的 select 语句
  • Query setFirstResult(int startPosition) 用于设置从哪个实体记录开始返回查询结果
  • Query setMaxResults(int maxResult) 用于设置返回结果实体的最大数。与 setFirstResult 结合使用可实现分页查询
  • Query setFlushMode(FlushModeType flushMode) 设置查询对象的 Flush 模式。参数可以取 2 个枚举值
    • FlushModeType.AUTO 为自动更新数据库记录
    • FlushModeType.COMMMIT 为直到提交事务时才更新数据库记录
  • setHint(String hintName, Object value) 设置与查询对象相关的特定供应商参数或提示信息。参数名及其取值需要参考特定 JPA 实现库提供商的文档。如果第二个参数无效将抛出 IllegalArgumentException 异常
  • setParameter(int position, Object value) 为查询语句的指定位置参数赋值。position 指定参数序号,value 为赋给参数的值
  • setParameter(int position, Date d, TemporalType type) 为查询语句的指定位置参数赋 Date 值。position 指定参数序号,value 为赋给参数的值,type 取 TemporalType 的枚举常量,包括 DATE、TIME 及 TIMESTAMP 三个,用于将 Java 的 Date 型值临时转换为数据库支持的日期时间类型(java.sql.Date、iava.sql.Time 及 java.sql.Timestamp)

2.3、select 语句

select 语句用于执行查询。其语法可表示为

select clause form_clause
	[where_clause]
	[groupby_clause]
	[having_clause]
	[orderby_clause]

2.4、from 子句

from 子句是查询语句的必选子句

  • select 用来指定查询返回的结果实体或实体的某些属性
  • from 子句声明查询源实体类,并指定标识符变量(相当于 SQL 表的别名)。如果不希望返回重复实体,可使用关键字 distinct 修饰。select、from 都是 JPQL 的关键字,通常全大写或全小写,建议不要大小写混用

2.5、查询所有实体

查询所有实体的 JPQL 查询字串很简单,例如:select o from Order oselect o from Orders as o

关键字 as 可以省去。标识符变量的命名规范与 Java 标识符相同,且区分大小写

调用 EntityManager 的 createQuery() 方法可创建查询对象,接着调用 Query 接囗的 getResultList() 方法就可获得查询结果集。例如:

Query query = entityManager.createQuery("select o from Order o");
List orders = query.getResultList();
Iterator iterator = orders.iterator();
while(iterator.hasNext()){
    //处理 Order
}

2.6、where 子句

where 子句用于指定查询条件,where 跟条件表达式。例:

select o from Orders o where o.id = 1;
select o from Orders o where o.id > 3 and o.confirm = 'true';
select o from Orders o where o.address.streetNumber >= 123;

JPQL 也支持包含参数的查询,例如:

select o from Orders o where o.id = :myId;
select o from Orders o where o.id = :myId and o.customer = :customerName;

注意:参数名前必须冠以冒号(

标签:Customer,customer0,SpringData,04,JPA,_.,where,id,select
来源: https://www.cnblogs.com/vectorx/p/16290698.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有