为什么 FetchType.EAGER 在单元测试中不起作用?

我的 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 中有效,但在测试中却不行?


Helenr
浏览 173回答 1
1回答

阿波罗的战车

我假设您没有将新用户添加到部门的用户列表中。您的构造函数必须如下所示:public User(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // other fields,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Department department) {&nbsp; &nbsp;// set all fields.&nbsp; &nbsp;department.getUsers().add(this);}在 Main 中它正在工作,因为您有两个事务,并且在读取中是在一个单独的事务中,并且 Department 是从 DB 中获取的。但是在单元测试中,它会从用户列表为空的内存中返回部门。在保存实体之前正确设置关系非常重要。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java