以下是在双向关系的子对象中分配父对象的方法?
假设您有一个说“一对多”的关系,那么对于每个父对象,都有一组子对象。在双向关系中,每个子对象都将引用其父对象。
eg : Each Department will have list of Employees and each Employee is part of some department.This is called Bi directional relations.
为此,一种方法是在保留父对象的同时在子对象中分配父对象
Parent parent = new Parent();
...
Child c1 = new Child();
...
c1.setParent(parent);
List<Child> children = new ArrayList<Child>();
children.add(c1);
parent.setChilds(children);
session.save(parent);
另一种方法是,您可以使用休眠拦截器,这样可以帮助您不必为所有模型编写以上代码。
Hibernate拦截器提供api在执行任何DB操作之前做自己的工作。就像对象的onSave一样,我们可以使用反射在子对象中分配父对象。
public class CustomEntityInterceptor extends EmptyInterceptor {
@Override
public boolean onSave(
final Object entity, final Serializable id, final Object[] state, final String[] propertyNames,
final Type[] types) {
if (types != null) {
for (int i = 0; i < types.length; i++) {
if (types[i].isCollectionType()) {
String propertyName = propertyNames[i];
propertyName = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
try {
Method method = entity.getClass().getMethod("get" + propertyName);
List<Object> objectList = (List<Object>) method.invoke(entity);
if (objectList != null) {
for (Object object : objectList) {
String entityName = entity.getClass().getSimpleName();
Method eachMethod = object.getClass().getMethod("set" + entityName, entity.getClass());
eachMethod.invoke(object, entity);
}
}
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
return true;
}
}
您可以将Intercepter注册为配置为
new Configuration().setInterceptor( new CustomEntityInterceptor() );