开发者

JPA @ManyToMany on only one side?

开发者 https://www.devze.com 2022-12-30 00:11 出处:网络
I am trying to refresh the @ManyToMany relation but it gets cleared instead... My Project class looks like this:

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 updat开发者_如何学Pythoned 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?


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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消