I'm developing an application which is moving data from one source (e.g. database) to another with some transformations made inbetween. So it is a kind of a data integration tool at the current point.
I want to show my problem with a simple example. Somehow I have the feeling that I do it the wrong way.
- I have List with objects from one source
- I go through these objects, make changes in data, convert them into different data types and then I save the data in a new object which is associated with the new database
Code:
public void makeItSo() {
GenericServiceDAOExport genExport = new GenericServiceDAOExport(); // Database 1
GenericServiceDAOImport genImport = new GenericServiceDAOImport(); // Database 2
List list = genExport.getAllObjects(new Bananna()); // getAllObjects from Database 1
if (list.size() > 0) {
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
Bananna bananna = (Bananna) iter.next();
// create new Apple model and set some attributes from the previouse source...
Apple appleImp = new Apple();
appleImp.setAppleId(bananna.getBanannaId());
appleImp.setName(bananna.getBanannaName())
// check if this recordset already exists - I have assigned IDs!
if (genImport.getObjectById(appleImp,appleImp.getAppleId()) == null) {
genImport.save(appleImp);
} else {
genImport.update(appleImp);
}
appleImp = null;
}
}
The Problem is that everytime the for loop starts I have to commit the transaction and close the session otherwise I get the error message:
Code:
a different object with the same identifier value was already associated with the session
Right now I do it in the save Method of GenericServiceDAOImport:
Code:
public void save(Object obj) {
Session session = HibernateUtilImport.getSession();
try {
HibernateUtilImport.beginTransaction();
session.save(obj);
HibernateUtilImport.commitTransaction();
HibernateUtilImport.closeSession();
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}
Question: I don't think this is the right way to do it! Is there any other way to create a set of objects (like above) and then commit the transaction when I finished with all objects? Besides my approach is awfully slow ....