Found shared references to a collection org.hibernate.HibernateException
Hibernate shows this error when you attempt to persist more than one entity instance sharing the same collection reference (i.e. the collection identity in contrast with collection equality).
Note that it means the same collection, not collection element - in other words relatedPersons
on both person
and anotherPerson
must be the same. Perhaps you're resetting that collection after entities are loaded? Or you've initialized both references with the same collection instance?
spring-data-jpa : Found shared references to a collection org.hibernate.HibernateException
It appears that you have multiple Phone
instances with the same Set
instance for person
. This can happen when you clone or copy a Phone
, or do something like phone1.setPerson(phone2.getPerson())
.
It's okay for the Person
s to be the same, but not the Set
itself. Each phone should create a new instance of a Set
that is only used within the entity.
You can make sure of this, by instantiating collections in the constructor or directly after declaration and then never calling the setter for the collection, e.g.
private Set<Person> person = new HashSet<Person>();
void addPerson(Person person) {
this.person.add(person);
}
and only use addPerson
, never setPerson
(you can add similar helper methods to add multiple persons, or remove a person, etc.).
You can also return a copy of the set instead of the set itself in the getPerson
getter to be sure that the collection instance never leaks out.
Hibernate error: found shared references
This error can happen in some specific cases when you have kind of a 'loop' reference, but in this case you don't have a class with a field that uses this same class.
So the error has to be in a call to the method setApartmentPayers()
, you need to check all the calls to the method and ensure that you are not assigning the same collection to two different entities.
Found shared references to a collection many to many relation
As I understand your code, you're trying to create a Movie
in database and bind it to the current User
. Correct me if I'm wrong.
At first, as you may learn from Hibernate User Guide, bidirectional @ManyToMany association should be defined and used differently.
A bidirectional @ManyToMany association has an owning and a mappedBy side. To preserve synchronicity between both sides, it’s good practice to provide helper methods for adding or removing child entities.
Secondly, you should not use CascadeType.ALL
on @ManyToMany
associations:
For @ManyToMany associations, the REMOVE entity state transition
doesn’t make sense to be cascaded because it will propagate beyond the
link table. Since the other side might be referenced by other entities
on the parent-side, the automatic removal might end up in a
ConstraintViolationException.For example, if @ManyToMany(cascade = CascadeType.ALL) was defined and
the first person would be deleted, Hibernate would throw an exception
because another person is still associated with the address that’s
being deleted.
So, we should move cascade
to the owning side, change cascade type, provide helper methods to the User
and update only the owning side (User
) of the association in our business logic. Let's change the code.
User model:
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "user_movie",
joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "movie_id", referencedColumnName = "id")
)
private Set<Movie> movies = new HashSet<>();
public void addMovie(Movie movie) {
movies.add(movie);
movie.getUsers().add(this);
}
public void removeMovie(Movie movie) {
movies.remove(movie);
movie.getUsers().remove(this);
}
Movie model:
@ManyToMany(mappedBy = "movies")
private Set<User> users = new HashSet<>();
And business logic:
@Override
public Movie createMovie(Movie movie) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
JwtUser user = (JwtUser)authentication.getPrincipal();
User current_user = userRepository.findOne(user.getId());
current_user.addMovie(movie);
userRepository.save(current_user);
return movie;
}
Found shared references to a collection: OneToMany empty collections refering to same PersistentBag
What you have here isn't a @OneToMany
relationship, since multiple Contract
entities may reference the same (set) of PricebookEntry
instances.
To fix turn the Collection<PricebookEntry>
into a proper entity Pricebook
and have a many-to-one relationship from Contract
to Pricebook
.
Also lose the now redundant pricebookid
since it is simply the id of the Pricebook
.
Hibernate 5 Exception: Found shared references to a collection
I figured this one out, but it took quite a bit of time. As I added more logging into a variety of methods in our company code (not the hibernate code), I found that somehow we were jumping into the hibernate code twice.
In the company I was working at, we had some Hibernate Listeners, and this code was rather old. I actually posted more of this on the Hibernate support boards. With the help of the Hibernate Developers, I found a much better way to have code for the Listeners, the approved way, and when I did that, it solved our issue.
We were able to write code to the database, but with the listeners making sure we only jumped into the Hibernate code ONCE, not TWICE. This made the issue go away. I will come back and update this story when I have more details.
Related Topics
Java Sorting Based on Enum Constants
How to Run Ssh Commands on Remote System Using Java
Threads Configuration Based on No. of Cpu-Cores
Can a Class Have No Constructor
Writing Custom Kafka Serializer
@Transactional(Propagation=Propagation.Required)
How Does Java Makes Use of Multiple Cores
Java Static Serialization Rules
Print All the Spring Beans That Are Loaded
Close One Jframe Without Closing Another
Is There a Java Equivalent to C#'s 'Yield' Keyword
Which Loop Has Better Performance? Why
Creating an Animated 4X4 Grid in Java
Why Does Java Switch on Contiguous Ints Appear to Run Faster with Added Cases