Forums Register Login

Hibernate Spring repository returns new object and therefore breaks references between objects

+Pie Number of slices to send: Send
Hi guys, I am having issues with hibernate within spring and would really appreciate any help.

The scenario is that I have a many-to-many relationship between objects "student" and "module"where a module contains a list of students, and a student contains a list of modules,

The idea being that I can modify all student objects belonging to a module when something changes, and equally allow the student objects to immediately pick up changes, should something change in the module.

The issue is that every time I pull from the db, the repository returns a new object, with a new hashcode meaning The Module objects contained in Student no longer point to the Module Objects in the DB, and vice-versa.

The repository is @Autowired

The student object is added to the principal so I don't need to call the DB every time a page loads.

As an exmaple of what I mean:
The original object is created, added to Student and persisted to the db. It looks like this:


The user then navigates to a new page where the module object is pulled from the db and compared to the one in the student object:


As you can see it is an object with the same attributes, a clone of the original but a completely different object with a different reference. So If I update this object, the Module object residing in student will be unaffected As the reference equality check shows.



Th student object holds a reference to the originally persisted object, while the object grabbed from the db is a new object.



Here is my hibernate setup:
Student:


Module:






I know this is a lot to read, so any help would be greatly appreciated!
+Pie Number of slices to send: Send
I can't see the images you posted (the domain is blocked in my office), but you can try to override the equals and hashCode methods in your Entity classes. Check this documentation which recommends overriding these methods in situations similar to yours...
I love a good mentalist. And so does this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 25571 times.
Similar Threads
How to link existing record from database table in ManyToMany Uni-directional relationship
Why is my Hibernate Search query not working?
The link table of ManyToMany annotation is not updated in Hibernate
EJB QL w/ ManyToMany
Implementation of association classes and mapping in hibernate
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 04:37:03.