JPA CascadeType.TODO no elimina huérfanos


Estoy teniendo problemas para eliminar nodos huérfanos usando JPA con la siguiente asignación

@OneToMany (cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "owner")
private List<Bikes> bikes;

Tengo el problema de los roles huérfanos colgando alrededor de la base de datos.

Puedo usar la anotación org.hibernate.annotations.Cascade Etiqueta específica de Hibernación, pero obviamente no quiero vincular mi solución a una implementación de Hibernación.

EDITAR : Parece que JPA 2.0 incluirá soporte para esto.

Author: rtruszk, 2008-11-20

11 answers

Si lo está usando con Hibernate, tendrá que definir explícitamente la anotación CascadeType.DELETE_ORPHAN, que se puede usar junto con JPA CascadeType.ALL.

Si no planea usar Hibernate, primero tendrá que eliminar explícitamente los elementos secundarios y luego eliminar el registro principal para evitar cualquier registro huérfano.

Secuencia de ejecución

  1. obtener la fila principal para ser eliminada
  2. recuperar elementos secundarios
  3. eliminar todos los elementos secundarios
  4. suprimir la fila principal
  5. cerrar sesión

Con JPA 2.0, ahora puede usar la opción orphanRemoval = true

@OneToMany(mappedBy="foo", orphanRemoval=true)
 144
Author: Varun Mehta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-16 12:39:03

Si está utilizando JPA 2.0, ahora puede usar el atributo orphanRemoval=true de la anotación @xxxToMany para eliminar huérfanos.

En realidad, CascadeType.DELETE_ORPHAN ha sido obsoleto en 3.5.2-Final.

 108
Author: Kango_V,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-08 22:40:09
╔═════════════╦═════════════════════╦═════════════════════╗
║   Action    ║  orphanRemoval=true ║   CascadeType.ALL   ║
╠═════════════╬═════════════════════╬═════════════════════╣
║   delete    ║     deletes parent  ║    deletes parent   ║
║   parent    ║     and orphans     ║    and orphans      ║
╠═════════════╬═════════════════════╬═════════════════════╣
║   change    ║                     ║                     ║
║  children   ║   deletes orphans   ║      nothing        ║
║    list     ║                     ║                     ║
╚═════════════╩═════════════════════╩═════════════════════╝
 43
Author: Sergii Shevchyk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-05 07:22:58

Si está utilizando JPA con EclipseLink, tendrá que establecer la anotación @PrivateOwned.

Documentación: Eclipse Wiki-Usando las extensiones JPA de EclipseLink-Capítulo 1.4 Cómo usar la Anotación @PrivateOwned

 12
Author: uı6ʎɹnɯ ꞁəıuɐp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-01 12:01:22

Puedes usar @PrivateOwned para eliminar huérfanos por ejemplo,

@OneToMany(mappedBy = "masterData", cascade = {
        CascadeType.ALL })
@PrivateOwned
private List<Data> dataList;
 7
Author: reshma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-08 11:03:04

Según Persistencia Java con Hibernación, cascade orphan delete no está disponible como anotación JPA.

Tampoco es compatible con JPA XML.

 4
Author: toolkit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-20 17:38:10

Acabo de encontrar esta solución, pero en mi caso no funciona:

@OneToMany(cascade = CascadeType.ALL, targetEntity = MyClass.class, mappedBy = "xxx", fetch = FetchType.LAZY, orphanRemoval = true) 

OrphanRemoval = true no tiene efecto.

 4
Author: Valéry Stroeder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-31 13:02:07

Solo @OneToMany(cascade = CascadeType.ALL, mappedBy = "xxx", fetch = FetchType.LAZY, orphanRemoval = true).

Remove targetEntity = MyClass.clase , es un gran trabajo.

 2
Author: Kohan95,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-31 13:27:44

Tuve el mismo problema y me pregunté por qué esta condición a continuación no eliminó a los huérfanos. La lista de platos no se eliminó en Hibernación (5.0.3.Final) cuando ejecuté una consulta llamada delete:

@OneToMany(mappedBy = "menuPlan", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Dish> dishes = new ArrayList<>();

Entonces recordé que yo no debo usar una consulta llamada delete, sino el EntityManager. Como usé el método EntityManager.find(...) para obtener la entidad y luego EntityManager.remove(...) para eliminarla, también se eliminaron los platos.

 2
Author: Bevor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-01 17:39:06

Para los registros, en OpenJPA antes de JPA2 era @ElementDependant.

 1
Author: Simone Gianni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-18 16:35:15

Estaba usando mapeo uno a uno, pero child no estaba siendo eliminado JPA estaba dando violación de clave foránea

Después de usar orphanRemoval = true, el problema se resolvió

 0
Author: vipin chauhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-13 06:27:17