以下是在双向关系的子对象中分配父对象的方法:
假设您有一个关系,比如一对多,则对于每个父对象,存在一组子对象。
在双向关系中,每个子对象都将引用其父对象。
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 Interceptor来实现,这样可以帮助你避免为所有的模型编写上述代码。
Hibernate拦截器提供了一些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() );