@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