Hibernate: Removing item from a List does not persist

前端 未结 4 1452
旧时难觅i
旧时难觅i 2020-12-06 09:59

I am having trouble when removing an item from a list. The list is defined in a superclass, but the Hibernate annotations are applied to property accessors in a subclass. Th

相关标签:
4条回答
  • 2020-12-06 10:51

    You have marked the 'content' field as transient in the super class. I would at least suspect that this is causing problems. With the mapping in the subclass, you basically have now two contradicting mappings for the same attribute.

    0 讨论(0)
  • 2020-12-06 10:57

    You have to explicitly specify cascade as CascadeType.DELETE_ORPHAN.

    Try to change code to

    @OneToMany    
    @Cascade(cascade = {CascadeType.ALL, CascadeType.DELETE_ORPHAN}, mappedBy = "temporal")
    

    Part from hibernate docs:

    If the child object's lifespan is bounded by the lifespan of the parent object, make the parent a full lifecycle object by specifying CascadeType.ALL and org.hibernate.annotations.CascadeType.DELETE_ORPHAN (please refer to the Hibernate reference guide for the semantics of orphan delete)

    0 讨论(0)
  • 2020-12-06 11:00

    Try removing the calls to Session.refresh(). From the docs:

    Re-read the state of the given instance from the underlying database. It is inadvisable to use this to implement long-running sessions that span many business tasks. This method is, however, useful in certain special circumstances. For example

    • where a database trigger alters the object state upon insert or update
    • after executing direct SQL (eg. a mass update) in the same session
    • after inserting a Blob or Clob

    http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html#refresh(java.lang.Object)

    If you call flush() before refresh(), that might fix the problem too, since flush() guarantees that any pending SQL will be executed against the DB. In practice I've almost never seen anyone use refresh() and it doesn't look like from your code that you need it.

    This chapter from the documentation is worth a read:

    http://www.hibernate.org/hib_docs/v3/reference/en/html/objectstate.html

    0 讨论(0)
  • 2020-12-06 11:01

    This is the currently recommended way.

    @OneToMany(mappedBy = "temporal", orphanRemoval = true, cascade = CascadeType.ALL)
    
    0 讨论(0)
提交回复
热议问题