Using PostgreSQL, why doesn't Hibernate/JPA create cascade constraints?

坚强是说给别人听的谎言 提交于 2019-12-03 13:45:57

Hibernate manages cascade operations itself manually. What is more, if you would make cascades on database, and not declare them in Hibernate (for performance issues) you could in some circumstances get errors. This is because Hibernate stores entities in its session cache, so it would not know about database deleting something in cascade.

When you use second-level cache, your situation is even worse, because this cache lives longer than session and such changes on db-side will be invisible to other sessions as long old values are stored in this cache.

I've read a bit Hibernate sources (really unpleasant experience) and I doubt it is under any circumstances possible to manage cascades on database side - there are too many assumptions made by Hibernate design that are incompatibile with DB reality.

Using

 cascade = CascadeType.ALL

causes hibernate to traverse this relationship if you perform any operation. It doesn't influence generated DLL.

If you want to delete all entities in fooSet add orphanRemoval attribute.

@OneToMany(cascade = CascadeType.ALL, mappedBy = "bar", orphanRemoval=true)

Also using

<property name="generateDdl" value="true" />

is good ONLY for development environment. Don't use it for production. (e.g. hibernate can't know how to change table schema if you for example rename a property/column wil create another column and maybe even drop the previous one).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!