1

I have a Java application that uses Spring Data (with JPA and Hibernate) to interact with the database though service and repository layers. Most of it works fine, but I have a problem testing the save call for composed objects:

Involved are three objects:

  • object A I get from the database
  • object B I create a new instance of in the test
  • object C I want to save to the database that has a many to one relationship to object A and a one to one relationship to object B (and instances of both attached to it)

(Cascade is set to merge and persist)

Now when trying to use the service for object C to save it, I get a detached entity exception. When putting @Transactional on top of the test method I can't check the state of the database, because the transaction is still open. (Putting retrieval and creation of the objects + the save call in a separate method with @Transactional didn't do anything at all. Trying to grab the entity manager and flush it did not help either.)

I'm sure this could be a common issue (or just misunderstanding from my side), but I haven't found any solution and would appreciate any advice.

versions in use:

  • Spring 4.0.5
  • JPA 2.1
  • Hibernate 4.3.5

2 Answers 2

0

You have to persist object B first or add the cascade attribute to the relationship annotation, e.g.

@OneToMany(cascade = CascadeType.ALL, mappedBy = "field")

This would cascade all operations through the relationship.

1
  • thanks for your reply, but cascade types are already set to MERGE and PERSIST Sep 10, 2014 at 15:11
0

Updating to Spring 4.1.0 helped me solving this issue. In Spring 4.1.0 is a new class TestTransaction that can commit during a transaction (I need in my case a @Transactional to avoid detached entities) and so you can check the state of the database.

It seems like you have to close the connection to actually commit and reopen it again to check the database. I used a commit call like this:

private void commit() {
    TestTransaction.flagForCommit();
    TestTransaction.end();
    TestTransaction.start();
}

If you know of an easier/better use, please tell me. But this did the trick for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.