mercredi 30 janvier 2019

Why EntityGraph doesn't fetch related entity in JUnit test?

I have two enitities in my JPA/Hibernate application - Task and 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();
    }
}

But when I run my test

    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 shows that list of timerecords in task entity is empty!

The interesting moment: if I run Main class, get ApplicationContext and run the same code is in my test - everything is OK! Inside task entity list of timerecords contains one timerecord.

Aucun commentaire:

Enregistrer un commentaire