为什么EntityGraph不取的JUnit测试相关实体?

时间:2019-01-30 19:37:17

标签: hibernate jpa testing fetch entitygraph

我的JPA / Hibernate应用程序中有两个实体-任务和时间记录。

任务

@NamedEntityGraph(
        name = "Task.timerecords",
        attributeNodes = {
                @NamedAttributeNode(value = "timerecords", subgraph = "timerecords"),
        }
)
@Entity(name = "tasks")
@Table(name = "tasks", schema = "myschema")
public class Task {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(columnDefinition = "BINARY(16)", length = 16 )
    private UUID uuid;

    @NotNull
    @Column(name = "description", nullable = false)
    private String description;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "task", cascade = CascadeType.ALL, orphanRemoval = true)
    List<Timerecord> timerecords = new ArrayList<>();
    //some more code
}

Timerecord

@Entity(name = "timerecords")
@Table(name = "timerecords", schema = "myschema")
public class Timerecord {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(columnDefinition = "BINARY(16)", length = 16 )
    private UUID uuid;

    @NotNull
    @Column(name = "hours", nullable = false)
    private double hours;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "tasks_uuid", nullable = false)
    private Task task;
    //some more code
}

TaskDao

@Repository("taskDao")
public class TaskDao {

    @PersistenceContext
    private EntityManager entityManager;

    public List<Task> getAllWithTimerecords(){
         EntityGraph graph = entityManager.createEntityGraph("Task.timerecords");

        return entityManager.createQuery("from tasks", Task.class)
                .setHint("javax.persistence.fetchgraph", graph)
                .getResultList();
    }
}

但是当我运行测试

    Task task = new Task(...);
    Timerecord tr = new Timerecord(...);
    UUID taskUuid = taskDao.save(task);
    assertNotNull(taskUuid);
    UUID trUuid = timerecordDao.save(tr);
    assertNotNull(trUuid);

    tasks = taskDao.getAllWithTimerecords();
    assertEquals(1, tasks.size());
    assertEquals(1, tasks.get(0).getTimerecords().size()); //AssertionFailedError: Expected :1 Actual   :0

Debug显示任务实体中的时间记录列表为空!

有趣的时刻::如果我运行Main类,则获取ApplicationContext并运行相同的代码正在测试中-一切正常!内部任务实体的时间记录列表包含一个时间记录。

0 个答案:

没有答案