在双向关系的子对象中分配父对象的方法有哪些?
假设您有一个关系说一对多,那么对于每个父对象,都存在一组子对象。
在双向关系中,每个子对象都会引用其父对象。
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 拦截器在执行任何 DB 操作之前提供 api 来完成您自己的工作。同样的对象的 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;
}
}
您可以将拦截器注册为配置
new Configuration().setInterceptor( new CustomEntityInterceptor() );