here are my requirements:
- I have an existing db scheme which I cannot change.
- I have one parent table and several child tables.
- All child tables have key columns of same format but different names.
- The concrete set of child tables differs for different installations.
- For reference integrity sake I need all child entities removed when the parent entity is removed.
- I don't need this cascade removal being managed by Hibernate, I control the removal myself by means of some delete() method.
So my possible solution shall look like the following:
- I inherit all children classes from one superclass or interface, say Child
- In the parent entity class I add @OneToMany field of type Set
- When the parent entity is removed I call delete() for all children.
Solutions that would not work:
- The Table per concrete class inheritance strategy would not work, since key columns in child tables have different names, this is not supported by hibernate.
- Adding a @OneToMany field to parent for each child table would not work since the set of child tables differs for each installation. So they must not be explicitly references in the parent.
发布评论
评论(1)
我认为唯一的解决方案是让每个安装提供所有子类的列表,并有一个循环这些类的方法,选择具有即将删除父级的所有实例,然后删除它们
:也可以直接使用删除 HQL 查询,但这会绕过会话。
如果每个子类使用不同的字段/属性名称引用父级,则将子类列表转换为
Map, String>
,其中 String 值是父级字段/子类的属性名称。如果您可以选择让所有子级继承一个 @MappedSuperClass 注解的类,其中声明并映射了父字段,则可以执行一个查询来返回所有子级:
但由于 Java 仅支持单继承,因此可能不是一个选择。
I think the only solution is to have each installation provide a list of all the child classes, and have a method that loops through these classes, select all the instances who have the soon-to-be-deleted parent, and remove them :
You could also use a delete HQL query directly, but this will bypass the session.
If each sublcass references the parent using a different field/property name, then transform the list of child classes into a
Map<Class<?>, String>
, where the String value is the parent field/property name for the child class.If you have the option to make all the children inherit a single @MappedSuperClass annotated class, where the parent field is declared and mapped, you could do a single query that would return all the children :
But since Java only supports single inheritance, it might not be an option.