Hibernate many-to-many association not updating join table - java

In my app, I have a many-to-many association between the User and Preference entities. Since the join table requires an additional column, I had to break it down into 2 one-to-many associations as such:
User entity :
#OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade={CascadeType.PERSIST, CascadeType.MERGE}, orphanRemoval = true)
public Set<UserPreference> getPreferences()
{
return preferences;
}
Preference entity :
#OneToMany(mappedBy = "preference", fetch = FetchType.EAGER)
public Set<UserPreference> getUserPreferences()
{
return userPreferences;
}
UserPreference entity :
#ManyToOne
#JoinColumn(name = "user_id", nullable = false)
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
#ManyToOne
#JoinColumn(name = "preference_id", nullable = false)
public Preference getPreference()
{
return preference;
}
public void setPreference(Preference preference)
{
this.preference = preference;
}
#Column(nullable = false, length = 25)
public String getValue()
{
return value;
}
public void setValue(String value)
{
this.value = value;
}
To update one of the preferences, I loop through the user's set of preferences and update the value as such:
#RequestMapping(value = {"/edit-{id}-preference"}, method = RequestMethod.POST)
public String updateUserPreference(#ModelAttribute("userPreference") UserPreference preference, BindingResult result, ModelMap model)
{
User loggedInUser = (User)session.getAttribute("loggedInUser");
for (UserPreference pref : loggedInUser.getPreferences())
{
if (Objects.equals(pref.getId(), preference.getId()))
{
pref.setValue(preference.getValue());
}
}
userService.update(loggedInUser);
return "redirect:/users/preferences";
}
I have confirmed that the user variable I'm trying to update does indeed contain the new value after this code runs. Even weirder, the value does update on the webpage when the redirect happens but the database does NOT update! This is the code I'm using to do the update, this class is annotated with #Transactional and every other call to this method (to update the user's role for example) works perfectly:
#Override
public void update(User user)
{
User entity = dao.findById(user.getId());
if (entity != null)
{
entity.setUserId(user.getUserId());
entity.setPassword(user.getPassword());
entity.setFirstName(user.getFirstName());
entity.setLastName(user.getLastName());
entity.setRole(user.getRole());
entity.setPreferences(user.getPreferences());
}
}
This acts like hibernate's session "cache" has the updated value but does not actually persist it. I am using this very same update method style for about 30 other entities and everything works fine. This is my only many-to-many association that I had to break down into 2 one-to-many associations so I have nothing to compare to.
Am I doing something wrong? When I create a user with a new HashSet and persist it, the value is written correctly in the "join table".
*****EDIT*****
For comparison, this is the code I use to create a new user with default preferences. The preferences exist already but the join table is completely empty and this code correctly persists the entities:
User user = new User();
user.setUserId("admin");
user.setPassword(crypter.encrypt("admin"));
user.setFirstName("admin");
user.setLastName("admin");
user.setRole(roleService.findByName("Admin"));
Set<UserPreference> userPreferences = new HashSet<>();
Preference preference = preferenceService.findByName("anchorPage");
UserPreference userPreference = new UserPreference();
userPreference.setUser(user);
userPreference.setPreference(preference);
userPreference.setValue("System Statistics");
userPreferences.add(userPreference);
preference = preferenceService.findByName("showOnlyActivePatients");
userPreference = new UserPreference();
userPreference.setUser(user);
userPreference.setPreference(preference);
userPreference.setValue("true");
userPreferences.add(userPreference);
user.setPreferences(userPreferences);
userService.save(user);
Thanks

Instead of
entity.setPreferences(user.getPreferences());
Do something like:
for( UserPreference uf : user.getPreferences() ) {
entity.getPreferences().add( uf );
}
The main difference here is that you aren't changing the list reference, which is managed by Hibernate, and is only adding elements to it.

How about using merge? That is what you are cascading after all and you have modified a detached object and need to merge back the changes:
public void update(User user) {
dao.merge(user);
}
EDIT: for clarity this replaces the old update method, so it should be called from the client side with loggedInUser, just like before.
EDIT 2: as noted in the comments merge will update all fields. The old update method also seems to do that? Optimistic locks (version numbers) can be used to guard against overwriting other changes by mistake.

Related

Can't delete parent without a child in Hibernate

I have two objects User and Workorder. One user can have multiple work orders. The problem is when I delete user it also deletes assigned work orders to that user. I have tried to set my work orders foreign keys to NULL before deleting the user but it still deletes all the associated work orders with that user. I'd like to delete user without deleting the work order assigned to user. What am I missing or doing wrong?
Here's is my User class:
#OneToMany(fetch = FetchType.LAZY, mappedBy="user", orphanRemoval=true)
private Set<WorkOrder> workOrder;
WorkOrder class:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="user_id", nullable = true)
private User user;
UserDAOImpl class:
#Override
public void deleteUser(int theId) {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// delete object with primary key
User user = currentSession.get(User.class, theId);
Set workorders = user.getWorkOrder();
Iterator<WorkOrder> work = workorders.iterator();
while (work.hasNext()){
WorkOrder workorder = work.next();
workorder.setUser(null);
}
currentSession.remove(user);
}
Remove that 'orphanRemoval=true' and check there's no 'cascade' on Workorder.user (if the relation is bidirectional)

Can I update only one relation (one field) using Hibernate

I have next relations:
#Entity
#Table(name = "STOCK", uniqueConstraints = #UniqueConstraint(columnNames = { "CODE", "INTERVAL", "DATE" }) )
public class StockEntity {
.....
many other fields like collections
.....
#ElementCollection
#CollectionTable(name = "PARAMETERS", joinColumns = #JoinColumn(name="SETTING_ID"))
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#MapKeyEnumerated(EnumType.STRING)
private Map<LocalSetting.SettingType, LocalSetting> parameters = new HashMap<>();
}
#Entity
#Table(name = "LOCAL_SETTING")
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class LocalSetting {
#Id
#Column(name = "SETTING_ID", unique = true, nullable = false)
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private long settingId;
.....
}
when I use my DAO:
#Override
public void updateStocks(List<StockEntity> stocks) {
Session session = sessionFactory.getCurrentSession();
stocks.forEach(stock -> {
session.update(stock);
session.flush();
session.clear();
});
}
in log trace i notice that will be updated all fields in StockEntity, when I was changing only "parameters",
it mean i also was updating lot of other parameters which i could simply skip
when I try to update only "parameters" using next code:
#Override
public void updateParameters(List<StockEntity> stocks) {
stocks.forEach(stock -> {
for (Map.Entry<LocalSetting.SettingType, LocalSetting> entry : stock.getParameters().entrySet()) {
sessionFactory.getCurrentSession().saveOrUpdate(entry.getValue());
}
});
}
but process will be same like i will update whole StockEntity
,maybe I can detach another fields until I will finish update "parameters"
As specified here
session.update()
update takes an entity as parameter.But you are passing a Map (which I assume are entities of LocalSetting that you want to save ).
And as far as I know it is not possible to persist a collection of objects using the update(..) method.
Try the following code to check if it works for you:
#Override
public void updateParameters(Map<LocalSetting.SettingType, LocalSetting> parameters)
{
for (Map.Entry<String, String> entry : map.entrySet())
{
sessionFactory.getCurrentSession().update(entry.getValue());
}
sessionFactory.getCurrentSession().commit();
sessionFactory.getCurrentSession().close();
}
What makes me suggest this answer more is the exception in your question(org.hibernate.MappingException) which is basically telling us that we are updating the entity which isnt mapped.
You have to use dynamic-insert in order to update only one field. The syntax is:
#org.hibernate.annotations.Entity(
dynamicInsert = true
)
You can see an example here: Dynamic insert example
You also can read this post why hibernate dynamic insert false by default in order to know problem you can have with dynamicInsert=true

JPA recursive one-to-one lazy-loaded reference not updated

Using JPA 2.1 and Hibernate 4.3.6.Final, I have the following simple entity:
#Entity
#Table(name = "CONTACT")
public class Contact {
#Id
#Column(name = "ID")
private String id = UUID.randomUUID().toString();
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "PARTNER_ID")
private Contact partner;
Contact() {
}
public void assignPartner(final Contact other) {
this.partner = Objects.requireNonNull(other);
other.partner = this;
}
public void unassignPartner() {
if (partner != null) {
partner.partner = null;
}
partner = null;
}
}
Notice the lazy-loaded one-to-one recursive association to a partner Contact. Also notice how assignPartner() and unassignPartner() manage the bi-directional relationship.
And the following methods:
private static void assignPartner(final EntityManager entityManager) {
entityManager.getTransaction().begin();
final Contact contact1 = entityManager.find(Contact.class, CONTACT1_ID);
final Contact contact2 = entityManager.find(Contact.class, CONTACT2_ID);
contact1.assignPartner(contact2);
entityManager.getTransaction().commit();
}
private static void unassignPartner(final EntityManager entityManager) {
entityManager.getTransaction().begin();
final Contact contact1 = entityManager.find(Contact.class, CONTACT1_ID);
contact1.unassignPartner();
entityManager.getTransaction().commit();
}
Assuming existing rows for CONTACT1_ID and CONTACT2_ID, after running assignPartner() then unassignPartner(), database state shows that contact1 has a null partner_id and contact2 still has a non-null partner_id.
However, if I change the Contact.partner fetch type to EAGER, after running assignPartner() then unassignPartner(), database state shows that both contact1 and contact2 have null partner_id.
Why is that? Why are changes to the partner entity not flushed to the database?
EDIT 1
Changes to the partner reference through direct field access, e.g. partner.firstName = "DUMPED", are not propagated either.
Changes to the partner reference through method access, e.g. partner.setFirstName("DUMPED"), are propagated.
Neither partner.partner = null or partner.setPartner(null) are propagated.
EDIT 2
As suggested by Rat2000, moving the unassignment logic outside the Contact.unassignPartner() method and inside the unassignPartner(EntityManager) method seems to work properly. So it's really something to do with how Hibernate deals with the contact1.partner proxy, and in particular the contact1.partner.partner proxy.
final Contact contact1 = entityManager.find(Contact.class, CONTACT1_ID);
contact1.getPartner().unassignPartner();
contact1.unassignPartner();
Try this:
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.UPDATE)
#JoinColumn(name = "PARTNER_ID")
private Contact partner;

Delete Not Working with JpaRepository

I have a spring 4 app where I'm trying to delete an instance of an entity from my database. I have the following entity:
#Entity
public class Token implements Serializable {
#Id
#SequenceGenerator(name = "seqToken", sequenceName = "SEQ_TOKEN", initialValue = 500, allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqToken")
#Column(name = "TOKEN_ID", nullable = false, precision = 19, scale = 0)
private Long id;
#NotNull
#Column(name = "VALUE", unique = true)
private String value;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "USER_ACCOUNT_ID", nullable = false)
private UserAccount userAccount;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "EXPIRES", length = 11)
private Date expires;
...
// getters and setters omitted to keep it simple
}
I have a JpaRepository interface defined:
public interface TokenRepository extends JpaRepository<Token, Long> {
Token findByValue(#Param("value") String value);
}
I have a unit test setup that works with an in memory database (H2) and I am pre-filling the database with two tokens:
#Test
public void testDeleteToken() {
assertThat(tokenRepository.findAll().size(), is(2));
Token deleted = tokenRepository.findOne(1L);
tokenRepository.delete(deleted);
tokenRepository.flush();
assertThat(tokenRepository.findAll().size(), is(1));
}
The first assertion passes, the second fails. I tried another test that changes the token value and saves that to the database and it does indeed work, so I'm not sure why delete isn't working. It doesn't throw any exceptions either, just doesn't persist it to the database. It doesn't work against my oracle database either.
Edit
Still having this issue. I was able to get the delete to persist to the database by adding this to my TokenRepository interface:
#Modifying
#Query("delete from Token t where t.id = ?1")
void delete(Long entityId);
However this is not an ideal solution. Any ideas as to what I need to do to get it working without this extra method?
Most probably such behaviour occurs when you have bidirectional relationship and you're not synchronizing both sides WHILE having both parent and child persisted (attached to the current session).
This is tricky and I'm gonna explain this with the following example.
#Entity
public class Parent {
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private Long id;
#OneToMany(cascade = CascadeType.PERSIST, mappedBy = "parent")
private Set<Child> children = new HashSet<>(0);
public void setChildren(Set<Child> children) {
this.children = children;
this.children.forEach(child -> child.setParent(this));
}
}
#Entity
public class Child {
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private Long id;
#ManyToOne
#JoinColumn(name = "parent_id")
private Parent parent;
public void setParent(Parent parent) {
this.parent = parent;
}
}
Let's write a test (a transactional one btw)
public class ParentTest extends IntegrationTestSpec {
#Autowired
private ParentRepository parentRepository;
#Autowired
private ChildRepository childRepository;
#Autowired
private ParentFixture parentFixture;
#Test
public void test() {
Parent parent = new Parent();
Child child = new Child();
parent.setChildren(Set.of(child));
parentRepository.save(parent);
Child fetchedChild = childRepository.findAll().get(0);
childRepository.delete(fetchedChild);
assertEquals(1, parentRepository.count());
assertEquals(0, childRepository.count()); // FAILS!!! childRepostitory.counts() returns 1
}
}
Pretty simple test right? We're creating parent and child, save it to database, then fetching a child from database, removing it and at last making sure everything works just as expected. And it's not.
The delete here didn't work because we didn't synchronized the other part of relationship which is PERSISTED IN CURRENT SESSION. If Parent wasn't associated with current session our test would pass, i.e.
#Component
public class ParentFixture {
...
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void thereIsParentWithChildren() {
Parent parent = new Parent();
Child child = new Child();
parent.setChildren(Set.of(child));
parentRepository.save(parent);
}
}
and
#Test
public void test() {
parentFixture.thereIsParentWithChildren(); // we're saving Child and Parent in seperate transaction
Child fetchedChild = childRepository.findAll().get(0);
childRepository.delete(fetchedChild);
assertEquals(1, parentRepository.count());
assertEquals(0, childRepository.count()); // WORKS!
}
Of course it only proves my point and explains the behaviour OP faced. The proper way to go is obviously keeping in sync both parts of relationship which means:
class Parent {
...
public void dismissChild(Child child) {
this.children.remove(child);
}
public void dismissChildren() {
this.children.forEach(child -> child.dismissParent()); // SYNCHRONIZING THE OTHER SIDE OF RELATIONSHIP
this.children.clear();
}
}
class Child {
...
public void dismissParent() {
this.parent.dismissChild(this); //SYNCHRONIZING THE OTHER SIDE OF RELATIONSHIP
this.parent = null;
}
}
Obviously #PreRemove could be used here.
I had the same problem
Perhaps your UserAccount entity has an #OneToMany with Cascade on some attribute.
I've just remove the cascade, than it could persist when deleting...
You need to add PreRemove function ,in the class where you have many object as attribute e.g in Education Class which have relation with UserProfile
Education.java
private Set<UserProfile> userProfiles = new HashSet<UserProfile>(0);
#ManyToMany(fetch = FetchType.EAGER, mappedBy = "educations")
public Set<UserProfile> getUserProfiles() {
return this.userProfiles;
}
#PreRemove
private void removeEducationFromUsersProfile() {
for (UsersProfile u : usersProfiles) {
u.getEducationses().remove(this);
}
}
One way is to use cascade = CascadeType.ALL like this in your userAccount service:
#OneToMany(cascade = CascadeType.ALL)
private List<Token> tokens;
Then do something like the following (or similar logic)
#Transactional
public void deleteUserToken(Token token){
userAccount.getTokens().remove(token);
}
Notice the #Transactional annotation. This will allow Spring (Hibernate) to know if you want to either persist, merge, or whatever it is you are doing in the method. AFAIK the example above should work as if you had no CascadeType set, and call JPARepository.delete(token).
This is for anyone coming from Google on why their delete method is not working in Spring Boot/Hibernate, whether it's used from the JpaRepository/CrudRepository's delete or from a custom repository calling session.delete(entity) or entityManager.remove(entity).
I was upgrading from Spring Boot 1.5 to version 2.2.6 (and Hibernate 5.4.13) and had been using a custom configuration for transactionManager, something like this:
#Bean
public HibernateTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
return new HibernateTransactionManager(entityManagerFactory.unwrap(SessionFactory.class));
}
And I managed to solve it by using #EnableTransactionManagement and deleting the custom
transactionManager bean definition above.
If you still have to use a custom transaction manager of sorts, changing the bean definition to the code below may also work:
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
As a final note, remember to enable Spring Boot's auto-configuration so the entityManagerFactory bean can be created automatically, and also remove any sessionFactory bean if you're upgrading to entityManager (otherwise Spring Boot won't do the auto-configuration properly). And lastly, ensure that your methods are #Transactional if you're not dealing with transactions manually.
I was facing the similar issue.
Solution 1:
The reason why the records are not being deleted could be that the entities are still attached. So we've to detach them first and then try to delete them.
Here is my code example:
User Entity:
#Entity
public class User {
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
private List<Contact> contacts = new ArrayList<>();
}
Contact Entity:
#Entity
public class Contact {
#Id
private int cId;
#ManyToOne
private User user;
}
Delete Code:
user.getContacts().removeIf(c -> c.getcId() == contact.getcId());
this.userRepository.save(user);
this.contactRepository.delete(contact);
Here we are first removing the Contact object (which we want to delete) from the User's contacts ArrayList, and then we are using the delete() method.
Solution 2:
Here we are using the orphanRemoval attribute, which is used to delete orphaned entities from the database. An entity that is no longer attached to its parent is known as an orphaned entity.
Code example:
User Entity:
#Entity
public class User {
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user", orphanRemoval = true)
private List<Contact> contacts = new ArrayList<>();
}
Contact Entity:
#Entity
public class Contact {
#Id
private int cId;
#ManyToOne
private User user;
}
Delete Code:
user.getContacts().removeIf(c -> c.getcId() == contact.getcId());
this.userRepository.save(user);
Here, as the Contact entity is no longer attached to its parent, it is an orphaned entity and will be deleted from the database.
I just went through this too. In my case, I had to make the child table have a nullable foreign key field and then remove the parent from the relationship by setting null, then calling save and delete and flush.
I didn't see a delete in the log or any exception prior to doing this.
If you use an newer version of Spring Data, you could use deleteBy syntax...so you are able to remove one of your annotations :P
the next thing is, that the behaviour is already tract by a Jira ticket:
https://jira.spring.io/browse/DATAJPA-727
#Transactional
int deleteAuthorByName(String name);
you should write #Transactional in Repository extends JpaRepository
Your initial value for id is 500. That means your id starts with 500
#SequenceGenerator(name = "seqToken", sequenceName = "SEQ_TOKEN",
initialValue = 500, allocationSize = 1)
And you select one item with id 1 here
Token deleted = tokenRepository.findOne(1L);
So check your database to clarify that
I've the same problem, test is ok but on db row isn't deleted.
have you added the #Transactional annotation to method? for me this change makes it work
In my case was the CASCADE.PERSIST, i changed for CASCADE.ALL, and made the change through the cascade (changing the father object).
CascadeType.PERSIST and orphanRemoval=true doesn't work together.
Try calling deleteById instead of delete on the repository. I also noticed that you are providing an Optional entity to the delete (since findOne returns an Optional entity). It is actually strange that you are not getting any compilation errors because of this. Anyways, my thinking is that the repository is not finding the entity to delete.
Try this instead:
#Test
public void testDeleteToken() {
assertThat(tokenRepository.findAll().size(), is(2));
Optional<Token> toDelete = tokenRepository.findOne(1L);
toDelete.ifExists(toDeleteThatExists -> tokenRepository.deleteById(toDeleteThatExists.getId()))
tokenRepository.flush();
assertThat(tokenRepository.findAll().size(), is(1));
}
By doing the above, you can avoid having to add the #Modifying query to your repository (since what you are implementing in that #Modifying query is essentially the same as calling deleteById, which already exists on the JpaRepository interface).

How make both sides of many-to-many relation ships owner?

I have a class Group and a class User
where Group and User are many-to-many relation ship
If i change the groups of a user and save a user i want to update the groups
and vice versa where if i changed a user of a group and save the group i want the user to be updated
Do i have to set the mappedBy in both classes
Note : I am using eclipseLink
For a many-to-many relationship, you will need to update the relationship data on both sides in order to stay consistent.
Unfortunately there is no shortcut.
What you can do is to create a single method on either of the entities or a third class to encapsulate the consistent update.
Beware of infinite loops - do not implement the propagation to the other entity in both entity classes.
Roughly like this:
public class User
...
public void addGroup(Group g){
groups.add(g);
g.addUser(this);
}
or
public class Group
...
public void addUser(User u){
users.add(u);
u.addGroup(this);
}
I assume the presence of proper cascade settings on the relationship annotations.
There is a difference between owning a relation and a bidirectional reference. The former primarily concerns the layout of your database where the latter concerns your application logic. From your question, I assume that you want the latter. At the same time, it is generally recommendable that only one side of a relation owns a reference. You can easily create a bidirectional reference while keeping a clear collection owner by creating add and remove methods that enforce bidrection:
class Group {
#ManyToMany
private Collection<User> users = ... ;
public void addUser(User user) {
if(user != null && !users.contains(user)) {
users.add(user)
user.addGroup(this);
}
}
public void removeUser(User user) {
if(user != null && users.contains(user)) {
users.remove(user)
user.removeGroup(this);
}
}
}
class User {
#ManyToMany(mappedBy="users")
private Collection<Group> groups = ... ;
public void addGroup(Group group) {
if(group != null && !groups.contains(group)) {
groups.add(group)
group.addUser(this);
}
}
public void removeGroup(Group group) {
if(group != null && groups.contains(group)) {
groups.remove(group)
group.removeUser(this);
}
}
}
In this example, Group owns the relation what does however not affect the application logic. Be aware of the manipulation order in order to avoid infinite loops. Also, note that this code is not thread-safe.
I understand that for author it is a little bit late, but maybe it will be helpful for another readers.
You can achieve this by adding #JoinTable for both sides:
(cascading you can add by your needs)
public class Group {
....
#ManyToMany
#JoinTable(
name = "group_user",
joinColumns = #JoinColumn(name = "groups_id"),
inverseJoinColumns = #JoinColumn(name = "users_id"))
private List<User> users;
}
public class User {
....
#ManyToMany
#JoinTable(
name = "group_user",
joinColumns = #JoinColumn(name = "users_id"),
inverseJoinColumns = #JoinColumn(name = "groups_id"))
private List<Group> groups;
}

Categories

Resources