Here are ways to assign a parent to a child of a bidirectional relationship <
Suppose you have a one-to-many relationship, then for each parent object there is a set of child objects. In a bidirectional relationship, each child will have a reference to its parent.
eg : Each Department will have list of Employees and each Employee is part of some department.This is called Bi directional relations.
To achieve this, in one way, you must assign the parent to the child, keeping the parent
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);
Another way : you can use hibernate Intercepter, so you cannot write the code above for all models.
Hibernate interceptor provides apis to do your own work before doing any database operation. Like an onSave object, we can assign a parent object to child objects using reflection.
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; } }
And you can register Intercepter for configuration as
new Configuration().setInterceptor( new CustomEntityInterceptor() );
Sunil Kumar Sep 09 '16 at 9:13 2016-09-09 09:13
source share