Jpa/Hibernate ManyToOne 关联非主键列 延迟加载失效

倾然丶 夕夏残阳落幕 提交于 2019-11-28 22:12:52

@ManyToOne配置延迟加载,如果是关联主键列,

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "billid", insertable = false,updatable = false, nullable = false)
    private Bill bill ;
@Setter
@Getter
@Entity
@DynamicUpdate
@Table(name = "Bill")
public class Bill implements Serializable {

    /**
     * 主键
     */

    @Id
    @Column(name = "ID")
    private String id;

   @Column(name = "SID")
    private String sid;
}

延迟加载是正常的。

但如果关联的Address的是sid而不是id的话,就延时加载就有问题。如下代码:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "billid", referencedColumnName = "sid", insertable = false,updatable = false, nullable = false)
private Bill bill;

这时的解决方案,需要了解PersistentAttributeInterceptable的机制。

@DynamicUpdate
@Entity
@Setter
@Getter
@Table ( name ="BillDETAIL" )
public class BillDetail implements PersistentAttributeInterceptable, Serializable {
        @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "billid", referencedColumnName = "sid", insertable = false,updatable = false, nullable = false)
    @LazyToOne(LazyToOneOption.NO_PROXY)
    private Bill bill;

    public Bill getBill() {
        if (interceptor!=null) {
            return (Bill)interceptor.readObject(this, "bill", bill);
        }
        return bill;
    }

    public void setBill(BillView bill) {
        if (interceptor!=null) {
            this.billView = (Bill) interceptor.writeObject(this,"owner", this.bill,bill);
            return ;
        }
        this.bill = bill;
    }


    @Transient
       private PersistentAttributeInterceptor interceptor;

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

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


}

 

参考:

https://blog.csdn.net/johnf_nash/article/details/86557107     

https://blog.csdn.net/windsigirl123/article/details/60957632

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!