我有一个带有JPA和EcliseLink的JSF应用程序。有一个具有多个属性的实体,包括用于存储大型二进制数据的Lob类型。
我需要经常搜索实体并将它们显示在列表中。只有当用户想要查看时,才需要大二进制数据。
我可以有一个方法来懒加载二进制数据吗?还是我必须把它作为另一个具有一对一关系的实体拿出来?
您可以在要延迟加载的属性上使用字节码增强和@Basic(fetch=FetchType. LAZY)
:
<plugin>
<groupId>org.hibernate.orm.tooling</groupId>
<artifactId>hibernate-enhance-maven-plugin</artifactId>
<version>${hibernate.version}</version>
<executions>
<execution>
<configuration>
<failOnError>true</failOnError>
<enableLazyInitialization>true</enableLazyInitialization>
</configuration>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
或者您可以为同一个数据库表定义多个子实体。考虑到您有一个附件
表,其中有一个存储BLOB的content
列。
您可以映射公共基类中的非惰性属性:
@MappedSuperclass
public class BaseAttachment {
@Id
@GeneratedValue
private Long id;
private String name;
@Enumerated
@Column(name = "media_type")
private MediaType mediaType;
//Getters and setters omitted for brevity
}
如果您只需要获取非惰性属性,则需要一个仅扩展基类的实体:
@Entity @Table(name = "attachment")
public class AttachmentSummary extends BaseAttachment {}
这永远不会获取content
列。
如果您需要获取包括content
在内的所有列,那么您可以使用此实体:
@Entity @Table(name = "attachment")
public class Attachment
extends BaseAttachment {
@Lob
private byte[] content;
//Getters and setters omitted for brevity
}
可以很容易地完成。使用以下注释。
@Basic(fetch=Fetch Type. LAZY)