3

I am trying to get some tests to work without relying on the app's DB. The app is using JPA w/Hibernate. I have tried annotating the class with @Transactional on both the method and the class without success.

Here is the relationship in Employee.java:

@OneToMany(mappedBy = "manager", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Employee> directReports;

Here's the test, the last arg is the manager:

Employee ceo;
Employee evp;

@Before
public void setup() {
    ceo = new Employee("Name", "ceo", null);
    evp = new Employee("Name", "evp", ceo);
}

@Test
public void testThatDirectReportsAreAssignedWithoutPersistence() {
    assertNotNull(ceo.getDirectReports());
}
08Dc91wk
  • 4,254
  • 8
  • 34
  • 67
Joe Essey
  • 3,457
  • 8
  • 40
  • 69
  • How do you run your unit test? Why do you expect, that the list is populated, if you don't do it yourself? – dunni Sep 04 '15 at 13:49
  • can you post your constructor Employee(), As you are testing without any db, so no entity is persisted or linked to hibernate session, so you will not have any hibernate magic of auto mapping your associations.. – Anudeep Gade Sep 04 '15 at 13:51
  • 1
    Hibernate is completely irrelevant here. You're hust testing that `getDirectReports()` doesn't return null when called on `new Employee("Name", "ceo", null)`;. That depends entirely and exclusively on the constructor and on the `getDirectReports()` method of Employee. That you haven't posted. – JB Nizet Sep 04 '15 at 14:53

1 Answers1

0

What you have is a bidirectional relation. Hibernate will fill both ends of the relation automatically, but only if it reads it from the database. If you merely create or update the relation on one side without roundtrip to the database, it will not kick in to fix the other side. Nor does any other JPA implementation AFAIK.

For bidirectional relations, people usually resolve to constructions like this one: How to handle bidirectional relationships when constructing hibernate entities?, but that leads to messy code usually.

Even better: try to avoid bidirectional associations.

Community
  • 1
  • 1
GeertPt
  • 16,398
  • 2
  • 37
  • 61
  • Can you help me understand specifically why this is 'bi-directional?' Can you suggest an alternative approach here for a manager-employee scenario? Thanks! – Joe Essey Sep 09 '15 at 15:08