我有实体结构:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade = { CascadeType.ALL })
List<UserAgreement> userAgreements= new ArrayList<>();
}
@Entity
@Table(name = "user_agreements")
public class UserAgreement {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@ManyToOne(cascade = CascadeType.REFRESH)
@JoinColumn(name = "user_id")
private User user;
@ManyToOne(cascade = CascadeType.REFRESH)
@JoinColumn(name = "agreement_id")
private Agreement agreement;
}
@Entity
@Table(name = "agreements")
public class Agreement {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "agreement", cascade = { CascadeType.ALL })
List<UserAgreement> userAgreements = new ArrayList<>();
}
我正在使用Spring Boot和JpaRepository。当我使用AgreementRepository extends JpaRepository<Agreement, Long>
来保存协议和相关的UserAgreement时,它运行良好并将必要的字段级联到DB:
agreement.getUserAgreements().add(new UserAgreement(user, agreement, status));
agreementRepository.save(agreement);
但是,保存后,如果尝试检索user.getActiveUserAgreements()
,我会得到空列表。它没有刷新。
如何强制用户实体获取从另一方保存的List<UserAgreement>
?
答案 0 :(得分:0)
这种关系是双向的,因为应用程序更新了一个 关系的一面,对方也应该得到更新,并且 同步。在JPA中,与Java一样,它的责任在于 应用程序,或维护关系的对象模型。如果 你的应用程序添加到关系的一方,然后它必须添加 到了另一边。
这意味着您需要在创建关系时将UserAgreement
分配给User
。
答案 1 :(得分:0)
看起来像多对多关联。您可能可能会删除UserAgreement类。无论如何,为了支持它,你必须编写辅助方法addAgreement(),removeAgreement()等。在这里查看更多细节https://vladmihalcea.com/the-best-way-to-use-the-manytomany-annotation-with-jpa-and-hibernate/