Original address: http://blog.csdn.net/yaerfeng/article/details/7387871
Java Hibernate object
I have a problem today. Rather distressed.
The requirements are as follows: There are 2 objects with the same ID, but their values are different. The property value of one of the objects to use for another object.
2 objects with the same ID cannot be present in the Sessionfactory (). GetSession of Hibernate. So come up with a copy of the object.
Looking for a lot of places, found that there are 2 ways to achieve the purpose of copying objects, but the last method still does not solve my problem. Just write it down.
1, Cloning clone
Java supports cloning an object's value to another object, simple cloning and deep cloning, deep cloning may include inheritance, nesting, not used, so there is no way to study it.
First, the cloned object needs to implement the Cloneable interface, overriding the Clone () method, in order for the Clone () method to be available externally, the overridden method access modifier needs to be changed to the public level.
[Java] view plain copy print? @Override public Object Clone () throws Clonenotsupportedexception {return super.clone (); }
@Override Public
Object Clone () throws Clonenotsupportedexception {return
super.clone ();
}
[Java]View Plain copy print? dv= (Deliverymanreport) Deliverymanreport.clone ()//Clone object
dv= (Deliverymanreport) Deliverymanreport.clone ()//Clone object
DV is an object of deliverymanreport cloning. It owns the cloned properties and methods.
2, serialization and deserialization of Serializable
The serialized object implements the serializable interface to achieve serialization.
After serialization, you can get the same object as the current object by deserializing it. It's more prepared than cloning. But it is not necessarily the best, if the object has been modified before, serialization may be a problem.
[Java] view plain copy print? Bytearrayoutputstream byteout = new Bytearrayoutputstream (); ObjectOutputStream out= New ObjectOutputStream (byteout); Out.writeobject (Deliverymanreport);//write Object, serialization Bytearrayinputstream Bytein = new Bytearrayinputstream ( Byteout.tobytearray ()); dv= (Deliverymanreport) in.readobject (); Read objects, deserializing
Bytearrayoutputstream byteout = new Bytearrayoutputstream ();
ObjectOutputStream out= New ObjectOutputStream (byteout);
Out.writeobject (Deliverymanreport);//write Object, serialization
Bytearrayinputstream Bytein = new Bytearrayinputstream ( Byteout.tobytearray ());
dv= (Deliverymanreport) in.readobject (); Read objects, deserializing
Serialization is often used for file-passing reads. Especially in the cache, the object can be cached on the hard disk by serialization. This is most common with information such as caching user rights and roles in the login system. It is also a good way to clone objects.