Answer the question
In order to leave comments, you need to log in
How to make a complete copy of an object, with all descendants in hibernate?
Hello! The system is based on Jboss Seam version 2.3.1. The system uses Java version 6, as well as Apache Tomcat acting as a server. Instead of EJBs, Spring Beans are used to run the application in a servlet container (Tomcat) instead of an application server (TomEE, GlassFish, Weblogic), and so on. Why this is done is not the point.
Versions of components used:
Jboss Seam 2.3.1
Spring Web 3.2.2
Spring Bean 3.2.2
Spring Remote
Hibernate 4.1.4
The problem is this. The entity save method (let's call it saveEntity()) receives a persistent object. I need in this method to make a copy of this object. The object has descendants, that is, it is also necessary to make a deep copy so that all links are saved. Roughly speaking, I need to save the same object, but with a different ID. After several days of reading answers on Google, and on StackOverflow in particular, I used several methods.
1) Use the following method as advised here :
public static <T> T clone(Class<T> clazz, T dtls) {
T clonedObject = (T) SerializationHelper.clone((Serializable) dtls);
return clonedObject;
}
public static <T> T initializeAndUnproxy(T entity) {
if (entity == null) {
return null;
}
try {
Hibernate.initialize(entity);
}
catch (Exception e) {
logger.error("Exception occured:", e);
}
if (entity instanceof HibernateProxy) {
entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer().getImplementation();
}
return entity;
}
public static Object clone(Object obj) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(100);
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
byte buf[] = baos.toByteArray();
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
ObjectInputStream ois = new ObjectInputStream(bais);
Object newObject = ois.readObject();
ois.close();
return newObject;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream(100);
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj); <--- тут валится
this.getSessionFactory().getCurrentSession().evict(entity);
((AEntity) entity).setEntryKey(null);
this.getSessionFactory().getCurrentSession().merge(entity);
Answer the question
In order to leave comments, you need to log in
I will not give an exact answer, but there is something to say about this:
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question