Jpa/Hibernate 字节码增强:字段延迟加载

JPA提供了@Basic注解,实现延迟加载字段的功能,如下:


    @Basic(fetch = FetchType.LAZY)
    @Column(name = "REMARK_CONTENT" )
    private String remarkContent;

但是实际上延迟加是不是起作用的,依然能够出这个字段的数据。

为了延迟加载生效,需要使用字节码增加的插件:

在pom文件中配置:

<plugin>
                <groupId>org.hibernate.orm.tooling</groupId>
                <artifactId>hibernate-enhance-maven-plugin</artifactId>
                <version>5.4.3.Final</version>
                <executions>
                    <execution>
                        <configuration>
                            <failOnError>true</failOnError>
                            <enableLazyInitialization>true</enableLazyInitialization>
                        </configuration>
                        <goals>
                            <goal>enhance</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

compile一下项目之后 ,再运行项目,即可看到效果。JPA只查询了我们需要的特定字段。

但这个有一个缺点,就是需要编译代码,

如果我们不想编译代码,仍然使用字节码增加的话,需要手工代码增加的代码:

    @Basic(fetch = FetchType.LAZY)
    @Column(name = "REMARK_CONTENT" )
    private String remarkContent;

    public String getRemarkContent() {
        if (interceptor!=null) {
            return (String) interceptor.readObject(this, "remarkContent", billView);
        }
        return remarkContent;
    }

    public void setRemarkContent(String remarkContent) {

        if (interceptor!=null) {
            this.remarkContent = (String) interceptor.writeObject(this,"owner", this.billView,billView);
            return ;
        }
        this.remarkContent = remarkContent;
    }

    @Transient
       private PersistentAttributeInterceptor interceptor;

    @Override
    public PersistentAttributeInterceptor $$_hibernate_getInterceptor() {
        return interceptor;
    }

    @Override
    public void $$_hibernate_setInterceptor(PersistentAttributeInterceptor interceptor) {
        this.interceptor = interceptor;
    }

配置完成!