简体   繁体   中英

Hibernate 2nd Level Cache: Update cached collection on creating of entity in oneToMany relation

I have the following class

@Entity(name = "table")
@Table(name = "table")
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class SomeClass {
    @Id
    long id;
    @OneToMany(mappedBy = "someObject")
    @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    private List<AnotherClass> anotherObjects;
}

And another class:

public class AnotherClass{
    @Id   
    long id;
    @ManyToOne
    @JoinColumn(name = "some_coulmn")
    SomeClass someObject;

}

The scenario is that when I create an object from type AnotherClass assigning it a certain someClass object and then retrieve that someClass object, I do not see the newly created object (unless I flush the cache and restart).

Is there anything I can do to update the collection representing the relation between two entities whenever a new entity is added to that relation?

Note: I am using hibernate 5.3 in Spring boot 2.1.8 project.

When you have a bi-directional relationship, I think it's usually advisable to update both ends. In your case, when creating an instance of AnotherClass and linking it to an instance of SomeClass, you should also add the AnotherClass into the corresponding anotherObjects List.

You'll find more detailed explanations in this question

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