首页 > 解决方案 > Entity in OneToMany collection is not updated

问题描述

Assume the following model:

@Entity
public class A {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

   @OneToMany(mappedBy = "a", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
   private List<B> bs;

   public B getB(long id) {
      for(B b : bs)
         if(b.getId() == id) {
            return b;
         }
   }

}

@Entity
public class B {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

   @ManyToOne
   @JoinColumn(name = "a_id")
   private A a;

   private String someString;

}

I then try to update a property of some entity B :

@Transactional(rollbackFor = Exception.class)
public void doSomeWork() {
   A a = aRepository.findById(/* some id */);
   a.getB(/* */).setSomeString(/* some string */);
}

When the method returns, I expect the modified entity B to be updated (SQL UPDATE). For some reason, it doesn't happen. I suspect that the framework is only aware about additions/removals to the bs collection, but since every instance in the collection should be a managed entity, the framework should be aware of the changes.

Not sure what I'm missing here.


EDIT:

I created a repository to reproduce the issue:

https://github.com/mikomarrache/hibernate-spring-issue

If you comment lines 25-27 of the MyServiceImpl class, the save in line 22 is performed. However, if you uncomment these lines, it looks like the save in line 22 is ignored but the second save in line 27 is done, and of course it breaks the unique constraint on name. In order to test, simply run the unit test. No need to populate the database, there is an SQL script on the classpath that is executed at startup.

标签: javahibernatejpa

解决方案


推荐阅读