Java 对象关系上的eclipselink缓存
我有两个实体:Java 对象关系上的eclipselink缓存,java,jpa,eclipselink,Java,Jpa,Eclipselink,我有两个实体: @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 = "firstCustomerR
@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
}
在此代码中,关系大小增加,但由于在调用.getSecondCustomerRelationship()之前,列表大小未更改
如果@Cacheable(false)添加到CustomerRelationship,则.size()返回正确的列表大小。在显示的代码中,您似乎没有维护关系的双方。调用setSecondCustomerRelationship将设置它的一侧,这一侧控制数据库中的外键字段。但是java对象模型与更改不同步,除非您还将customerRelationship添加到CustomerMinInformation的集合中。JPA不会为你维护你的关系,所以如果你改变了一方,你就有责任让另一方保持同步 您可以设置双方,也可以在提交后强制从数据库刷新CustomerMinion信息。第一种选择要有效得多
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());