java - jpql 不加载 Blob

标签 java orm jpa lazy-loading blob

@Entity
@NamedQueries({
    @NamedQuery(name = "Item.findAll", query = "select i from Item i"),
})
public class Item implements Serializable, WithId, WithNameDescription {
    @Lob
    byte[] photo;
    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
    TextualInfo english = new TextualInfo();
// more entry field, getters and setters
}

当我调用查询 Item.findAll 时,我假设所有 bytes[] 都进入了内存。但我不会用它。所以我不想去取它。有没有办法,如何指定我想在 jpql 查询中延迟加载照片这一事实?

最佳答案

默认情况下,持久属性会被预先加载,您无法从 JPQL 中控制它。但是,您可以尝试更改默认行为并使用 Basic 注释使 photo 变得懒惰。来自 JPA 规范:

9.1.18 Basic Annotation

The Basic annotation is the simplest type of mapping to a database column. The Basic annotation can be applied to a persistent property or instance variable of any of the following types: Java primitive types, wrappers of the primitive types, java.lang.String, java.math.BigInteger, java.math.BigDecimal, java.util.Date, java.util.Calendar, java.sql.Date, java.sql.Time, java.sql.Timestamp, byte[], Byte[], char[], Character[], enums, and any other type that implements Serializable. As described in Section 2.1.6, the use of the Basic annotation is optional for persistent fields and properties of these types.

@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface Basic {
FetchType fetch() default EAGER;
boolean optional() default true;

The FetchType enum defines strategies for fetching data from the database:

public enum FetchType { LAZY, EAGER };

The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed. The implementation is permitted to eagerly fetch data for which the LAZY strategy hint has been specified. In particular, lazy fetching might only be available for Basic mappings for which property-based access is used.

像这样:

@Lob @Basic(fetch=LAZY)
public byte[] getPhoto() { return photo; }

但正如规范中所述,这只是一个提示,可能不受支持。在这种情况下,另一种方法是使用延迟加载的强制与另一个实体(持有 blob)的一对一关联。

引用资料

  • JPA 1.0 规范
    • 第 9.1.18 节“基本注释”
    • 第 9.1.19 节“Lob 注释”

关于java - jpql 不加载 Blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3568947/

相关文章:

java - 帮助处理 Hibernate (Spring) 中的外键映射?

python - Django 查询互相喜欢的用户

java - Spring Data JPA 保存列表实体返回列表的顺序相同吗?

java - JPA实体未映射异常

java - 每个帐户的 Hibernate/JPA 增量列

java - 将数组从 Delphi DLL 传递到 JNA

java - 在 apache tomcat 中部署应用程序时出错

Java ArrayList、LinkedList 和 Stack 问题

java - 线程新手需要java方面的建议

java - 热切/惰性加载成员始终为空,且具有 JPA 一对多关系