简体   繁体   中英

Get PersistentSet from EntityManager or Hibernate Session

Hibernate returns org.hibernate.collection.internal.PersistentSet as Set implementation on @OneToMany relation:

  @OneToMany(mappedBy = "group", cascade = CascadeType.PERSIST)
  private Set<Student> studentSet;

Hibernate tracks all changes on PersitanceSet (if some entity will is added to Set than it will be inserted into a database and etc.). Is it possible to have the same functionality for collections got by JPA EntityManager, org.hibernate.Session or by another way? For example:

entityManager.createQuery(query, Student.class)
                .setParameter("name", name)
                .getResultList();

Doesn't return such kind of collection.

So I am searching the way to get elements by custom query and collect elements into a collection that Hibernates tracks all changes(inserting on adding new transient entities, updating on changing managed entities, deleting on removing from the collection)

What you're asking for is not possible in Hibernate.

Hibernate tracks all changes on PersitanceSet (if some entity will is added to Set than it will be inserted into a database and etc.)

That statement is not really accurate. Hibernate will not automatically insert an entity added to the set into a database. You need to opt in for that functionality specifically by declaring the appropriate cascading option ( CascadeType.PERSIST in this case).

What Hibernate will do, however, is track associations between entities . If a collection represents the owning side of a to-many association, changes to the collection will establish/destroy associations between entities. In fact, Hibernate will track all other entity state, not just associations. That's the idea behind managed entities - to be able to work with a domain object just like with any other Java object, and let Hibernate take care about persistence behind the scenes.

A collection retrieved from a query does not represent part of a single entity state. Therefore, there would be little sense for Hibernate to track the structural state of the list. Suppose you made two queries for the same data within a single transaction. You then modify one of the result lists and leave the other intact. What do you think should happen in such a scenario?

Note that by 'not possible', I mean to say that Hibernate does not provide such a functionality out of the box. However, if you want to track changes to an arbitrary list, there are list implementations that allow that (see eg Glazed Lists or Apache Commons Events). You could combine them with Hibernate API to get the behavior you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM