Hibernate second level cache and ON DELETE CASCADE in database schema

你说的曾经没有我的故事 提交于 2019-12-05 06:55:23

If you are always going to delete through your program, you want to take the constraint off the database and tell the hibernate object to ON DELETE CASCADE to take care of the related guys.

On the other hand, if you are going to delete objects sometimes in your java app, and sometimes at your database level, you will end up with weird hanging data. In this case you may need to look into a more complicated approach.. You weren't clear if this was the case, so not going to go into more detail here.

If you are using ON DELETE CASCADE in your database you need to tell hibernate, like this:

@OnDelete(action = OnDeleteAction.CASCADE)

this is different from

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

The latter is telling hibenrate something about the in-memory relationship. the first one optimizes delete SQL Statements on the database level. Hibernate needs to know that the DB is taking care of delete childs.

Take a look at this site for a good explanation of this mechanism:

http://eddii.wordpress.com/2006/11/16/hibernate-on-deletecascade-performance/

and the comment from the developer of this feature:

http://www.mail-archive.com/hibernate-devel@lists.sourceforge.net/msg03801.html

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