我的 JPA (Hibernate) 和 Spring 應用程序。我的實體是:部門@Entity@Table(schema = "myschema")public class Department { @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") @Column(columnDefinition = "BINARY(16)", length = 16 ) private UUID uuid; @Column(name = "name", length = 200, nullable = false) private String name; @OneToMany(fetch = FetchType.EAGER, mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true) List<User> users = new ArrayList<>();}用戶@Entity@Table(schema = "myschema")public class User { @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") @Column(columnDefinition = "BINARY(16)", length = 16 ) private UUID uuid; @NotNull @Column(name = "login", length = 100, nullable = false) private String login; @ManyToOne @JoinColumn(name = "department_fk", nullable = false) private Department department;}部門DAO:@Repository("departmentDao")public class DepartmentDao { @PersistenceContext private EntityManager entityManager; @Transactional public UUID save(Department entity) { log.info("Department entity will be persisted", entity); entityManager.persist(entity); return entity.getUuid(); } @Transactional public List<Department> getAllWithUsers() { log.info("Select all departments"); CriteriaQuery<Department> criteria = entityManager.getCriteriaBuilder().createQuery(Department.class); Root<Department> root = criteria.from(Department.class); criteria.select(root); return entityManager.createQuery(criteria).getResultList(); }}當我在 Main 類中運行代碼時,它會加入實體:所以,我的問題是:為什么EAGER在 Main 中有效,但在測試中卻不行?
1 回答

阿波羅的戰車
TA貢獻1862條經驗 獲得超6個贊
我假設您沒有將新用戶添加到部門的用戶列表中。
您的構造函數必須如下所示:
public User(
// other fields,
Department department) {
// set all fields.
department.getUsers().add(this);
}
在 Main 中它正在工作,因為您有兩個事務,并且在讀取中是在一個單獨的事務中,并且 Department 是從 DB 中獲取的。
但是在單元測試中,它會從用戶列表為空的內存中返回部門。
在保存實體之前正確設置關系非常重要。
添加回答
舉報
0/150
提交
取消