views:

175

answers:

1

I am trying to refresh the @ManyToMany relation but it gets cleared instead...

My Project class looks like this:

@Entity
public class Project {
    ...
    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "PROJECT_USER",
    joinColumns = @JoinColumn(name = "PROJECT_ID", referencedColumnName = "ID"),
    inverseJoinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "ID"))
    private Collection<User> users;
    ...
}

But I don't have - and I don't want - the collection of Projects in the User entity.

When I look at the generated database tables, they look good. They contain all columns and constraints (primary/foreign keys).

But when I persist a Project that has a list of Users (and the users are still in the database), the mapping table doesn't get updated gets updated but when I refresh the project afterwards, the list of Users is cleared.

For better understanding:

Project project = ...; // new project with users that are available in the db
System.out.println(project getUsers().size()); // prints 5
em.persist(project);
System.out.println(project getUsers().size()); // prints 5
em.refresh(project);
System.out.println(project getUsers().size()); // prints 0

So, how can I refresh the relation between User and Project?

+1  A: 

The error seems to be in the code that you left out with ...

I am assuming that project actually did come out of the database (making persist a noop), otherwise you should be getting a hibernate exception when you try to refresh an entity that hasn't been committed yet.

There seems to just be some confusion here about the difference between JDBC and ORM and what an EntityManager actually does. em.persist is not a SQL insert or a SQL update. It says 'take this new entity and put it in the managed state.' Usually that eventually leads to a SQL insert, but that's not what it means at the application level.

It looks like you're essentially telling hibernate "I made some changes to this, next time the session is synchronized please persist them, oh, you know what, I changed my mind, revert back to what's in the database." em.persist does not directly put anything in the database, what's there is probably still "nothing".

Try tossing an em.flush in before your refresh and you should see your Users.

(You haven't said anything about how your session is configure or how you're managing transactions, so I'm assuming all of this is in one transaction.)

Affe
thanks... em.flush() did the trick!
Ethan Leroy
One is curious what is the functionality you're trying to achieve? Experimenting with that is an interesting academic investigation of how ORM works, but I don't know why you'd actually want to do it.
Affe
for UnitTesting...
Ethan Leroy