我有两个实体:
@Entity
public class CustomerMainInformation {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@Column(unique = true, length = 10)
private String customerNumber;
@OneToMany(mappedBy = "firstCustomerRelationship", cascade = CascadeType.ALL)
private List<CustomerRelationship> firstCustomerRelationship;
@OneToMany(mappedBy = "secondCustomerRelationship", cascade = CascadeType.ALL)
private List<CustomerRelationship> secondCustomerRelationship;
// setter & getter
}
@Entity
public class CustomerRelationship {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(columnDefinition = "first")
private CustomerMainInformation firstCustomerRelationship;
@ManyToOne
@JoinColumn(columnDefinition = "second")
private CustomerMainInformation secondCustomerRelationship;
// setter & getter
}
我执行了以下代码:
CustomerMainInformation customerMainInformation =manager.getReference(CustomerMainInformation.class, 1L);
System.out.println(customerMainInformation.getFirstCustomerRelationship().size());
System.out.println(customerMainInformation.getSecondCustomerRelationship().size());
CustomerMainInformation customerMainInformation2 = manager.getReference(customerMainInformation.getClass(), 2L);
CustomerRelationship customerRelationship = new CustomerRelationship();
customerRelationship.setFirstCustomerRelationship(customerMainInformation2);
customerRelationship.setSecondCustomerRelationship(customerMainInformation);
manager.persist(customerRelationship);
transaction.commit();
EntityManager manager2 = factory.createEntityManager();
CustomerMainInformation customerMainInformation3 = manager2.getReference(CustomerMainInformation.class, 1L);
System.out.println(customerMainInformation3.getFirstCustomerRelationship().size());
System.out.println(customerMainInformation3.getSecondCustomerRelationship().size());
在此代码中,关系大小增加,但由于调用了 .getSecondCustomerRelationship() 之前,列表大小未更改。
如果 @Cacheable(false) 添加到 CustomerRelationship,则 .size() 返回正确的列表大小。
最佳答案
在显示的代码中,您似乎没有维护双方的关系。调用 setSecondCustomerRelationship 会设置它的一侧,这一侧控制着 db 中的外键字段。但是您的 java 对象模型与您的更改不同步,除非您还将 customerRelationship 添加到 customerMainInformation 的集合中。 JPA 不会为您维护关系,因此如果您更改一侧,您有责任保持另一侧同步。
您可以同时设置两侧,也可以在提交后强制从数据库刷新 customerMainInformation。第一个选项效率更高。
关于java - eclipselink 缓存上的对象关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21539258/