Почему EntityGraph не выбирает связанный объект в тесте JUnit? - PullRequest
0 голосов
/ 30 января 2019

В моем приложении JPA / Hibernate есть два объекта - Task и Timerecord.

Task

@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

Отладка показывает, что список записей времени в объекте задачи пуст!

Интересный момент: , если я запускаю Main class, получаю ApplicationContext и запускаю тот же код в моем тесте - все в порядке!Внутри объекта задачи список временных записей содержит одну временную запись.

...