Hibernate 5 & JPA 2.1 延迟加载大字段属性

    xiaoxiao2021-03-25  120

    一、实体中有时会有一些字段所占用的空间比较大(如:大String),但一般又用不到的情况,这时就可以使用延迟加载的机制。

    @Entity public class Sutdent implements Serializable, PersistentAttributeInterceptable { private static final long serialVersionUID = 1L; private PersistentAttributeInterceptor interceptor; private String id; // 姓名 private String name; // 大字段属性 private String bigStr; // 课程 List<Course> courses; @Id @GeneratedValue public String getId() { return id; } @Basic(fetch = FetchType.LAZY) @LazyToOne(LazyToOneOption.NO_PROXY) public String getBigStr() { if (interceptor != null) { return (String) interceptor.readObject(this, "bigStr", bigStr); } return bigStr; } @OneToMany(fetch = FetchType.LAZY) @OrderBy(value = "id ASC") public List<Course> getCourses() { if (interceptor != null) { return (List<Course>) interceptor.readObject(this, "courses", courses); } return courses; } // get and set method... @Override public PersistentAttributeInterceptor $$_hibernate_getInterceptor() { return interceptor; } @Override public void $$_hibernate_setInterceptor(PersistentAttributeInterceptor interceptor) { this.interceptor = interceptor; } }

    二、注意事项:

    1、实现PersistentAttributeInterceptor的实体,重写PersistentAttributeInterceptor的get,set方法后才可以使用;

    2、PersistentAttributeInterceptor对原来的、添加了ManyToOne、OneToMany等非集合类属性不会产生影响;

    3、PersistentAttributeInterceptor对原来的、添加了ManyToOne、OneToMany等集合类则会产生影响,需要在方法中加上类似的代码,此外无需添加其他代码(注解等);

    转载请注明原文地址: https://ju.6miu.com/read-10293.html

    最新回复(0)