Using bidirectional associations from domain objects in @Transactional Junit Tests

I have installed the test JUnit Test @Transactional, and I want to save some test data in the database, and also check the correctness of the associations. However, when testing associations, they always evaluate to null, even though it works in the test without transactions.

I save two objects using the @Before annotation:

@Before
public void testData() {
    TestObjectOne o = new TestObjectOne();
    o.setName("One");
    repo.saveEntity(o); //autowired

    TestObjectTwo t = new TestObjectTwo();
    t.setOne(o);
    t.setName("Two");
    repo.saveEntity(t);
}

When accessing these two objects in the test, I get the correct instances:

    TestObjectOne o = repo.getOneByName("One");
    TestObjectOne t = repo.getTwoByName("Two");

When checking the connection between tand oI get the correct link because I explicitly defined this association:

    Assert.assertNotNull(t.getOne());

But when checking the opposite, the object is oincorrectly updated:

    Assert.assertNotNull(o.getTwos());

The relationship is defined in the domain object as

In One:

   @OneToMany(mappedBy = "one", fetch = FetchType.EAGER)
   private List<Two> twos;

In Two:

  @ManyToOne(optional = false)
  private One one;

, @Transactional, .

@Before .

+5
2

.

TestObjectOne o, Hibernate. TestObjectTwo t o , Hibernate. , get Hibernate, , , , . , - L1 , -.

public class MyTest {

    @Before
    public void setUp() {

        TestObjectOne o = new TestObjectOne();
        o.setName("One");
        repo.saveEntity(o); //autowired

        TestObjectTwo t = new TestObjectTwo();
        t.setOne(o);
        t.setName("Two");
        repo.saveEntity(t);

        /* push all changes to current transaction*/
        repo.getSessionFactory().getCurrentSession().flush();
        /* clean current session, so when loading objects they'll
           be created from sratch and will contain above changes */
        repo.getSessionFactory().getCurrentSession().clear();
    }

    @Test
    public void test() {
        TestObjectOne o = repo.getOneByName("One");
        TestObjectOne t = repo.getTwoByName("Two");

        Assert.assertNotNull(t.getOne());
        Assert.assertNotNull(o.getTwos());
    }
}
+4

@Transactional , .

, , @Rollback(false) @Transactional.

0

All Articles