【问题标题】:How to lazy load an entity attribute using JPA如何使用 JPA 延迟加载实体属性
【发布时间】:2013-05-21 21:07:06
【问题描述】:

我有一个带有 JPA 和 EclipseLink 的 JSF 应用程序。有一个实体具有多个属性,包括用于存储大型二进制数据的 Lob 类型。

我需要经常搜索实体并将它们显示在列表中。只有当用户想要查看时,才需要大二进制数据。

我可以有一种方法来延迟加载二进制数据吗?还是我必须将其作为另一个具有一对一关系的实体取出?

【问题讨论】:

    标签: java jpa orm persistence eclipselink


    【解决方案1】:

    您可以在要延迟加载的属性上使用字节码增强和@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>
    

    或者您可以为同一个数据库表定义多个子实体。考虑到您有一个 attachment 表,其中有一个存储 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
    }
    

    【讨论】:

    • 嗨@Vlad Mihalcea,如何使用子实体方法处理spring data jpa?
    【解决方案2】:

    可以轻松完成。使用以下注释。

    @Basic(fetch=FetchType.LAZY)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2021-11-19
    • 1970-01-01
    相关资源
    最近更新 更多