@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. TheLAZY
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 theLAZY
strategy hint has been specified. In particular, lazy fetching might only be available forBasic
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/