I have 2 tables (Customer and CustomerTemp) with same columns.
I am retrieving record from Customer table and adding to CustomerTemp table. Retrieved record is stored as custDetails object.
I am using following API:
void saveOrUpdate(String entityName,
Object object)
I have declared 2 entities namely Customer and CustomerTemp using @Entity Annotation. Entity name is used in saveOrUpdate API.
session.saveOrUpdate("CustomerTemp", custDetails);
to add/update same record into CustomerTemp table. Somehow hibernate is adding/updating record in Customer table.
As per documentation, hibernate should add record to CustomerTemp table. Not sure what is missing.
Update:
For Testing purpose, I have created 2 tables (table1 and table 2)
@Entity(name="mytable1")
public class table1 implements Serializable {
private static final long serialVersionUID = 3627342236515154416L;
@Id
@GeneratedValue
private int id;
@Column(length=20)
private String Name;
// Getters and setters...
}
@Entity(name="mytable2")
public class table2 implements Serializable {
private static final long serialVersionUID = -2203149737718957786L;
@Id
@GeneratedValue
private int id;
@Column(length=20)
private String Name;
// Getters and setters...
}
Now I have created object using table1 and tried to use saveOrUpdate with myTable2 entity expecting that record will be saved in table2. But record is always persisted to table1 irrespective of entity name provided in saveOrUpdate.
Session session = getSessionFactory().getCurrentSession();
Transaction tx ;
table1 tb1 = new table1();
tb1.setName("Shirish");
tx = session.beginTransaction();
session.saveOrUpdate("mytable2", tb1);
tx.commit();
Regards,
– Shirish
I am able to use approach specified in question by Cloning java objects. table1 is clone to create new table2 object. But this is really complex process where multiple *-to-Many relations involved.
Later I have tried to use XML approach to define table in hibernate. Please refer to
Mapping same POJO to more than one table in Hibernate XML mapping files for details. Please note that you may need to use session.clear() to deattach entity before using it in other DB operation.
Any other approach will be welcome.
In this case, Cloning in not required as we are defining tables based on same Java Object.
Regards,
Shirish