• 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;
        }

    配置完成!

  • 相关阅读:
    三种数据解析方式
    requests模块相关用法
    urllib模块基本用法
    django复习题
    scrapy框架编写向redis数据库中存储数据的相关代码时报错解决办法
    并发编程练习题
    网络编程 socket 开发练习题
    面向对象编程设计练习题(2)
    pytest-fixtured
    Python 删除某一目录下的所有文件或文件夹
  • 原文地址:https://www.cnblogs.com/hankuikui/p/11733877.html
Copyright © 2020-2023  润新知