我有两个实体:
@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()将返回正确的列表大小。
答案 0 :(得分:1)
您似乎没有在显示的代码中维护关系的两个方面。调用setSecondCustomerRelationship将设置它的一侧,并且此侧控制db中的外键字段。但是您的java对象模型与您的更改不同步,除非您还将customerRelationship添加到customerMainInformation的集合中。 JPA不会为您维护您的关系,因此如果您改变一方,则您有责任保持另一方不同意。
您可以设置双方,也可以在提交后强制从数据库刷新customerMainInformation。第一种选择效率更高。