Hi,
I have a table of documents.
I am trying to merge this table between two databases (cd -source db & hd - the target db)
by the following rule:
-Insert new records.
-If there is alreasy an existing record in the hd DB, compare
the dates of the document (if it's more updated then override the record in the hd DB).
I also manage two Lists of newDocs & updatedDocs.
Basically, I am using session.replicate(doc,ReplicationMode.EXCEPTION);
and when an exception is thrown (meaning the doc already exist, I am checking the dates.
Here is an example of the code:
public void handleDocumentsMerge() throws HibernateException
{
Session cdSession = m_cdDatasourceManager.getSession();
Session hdSession = m_hdDatasourceManager.getSession();
m_logger.debug("Read all records from Documents table in CD DB");
List documents = cdSession.createQuery("from Documents").list();
m_logger.debug("Insert new or updated docs to Documents table in HB DB");
Iterator iter=documents.iterator();
while(iter.hasNext())
{
Documents existDoc;
Documents doc=(Documents)iter.next();
try{
m_logger.debug("Handle document with document-id:"+doc.getDocumentid());
//try to insert the document, throw constraint exception if exist
hdSession.replicate(doc,ReplicationMode.EXCEPTION); hdSession.flush(); m_newDocs.add(doc);
}
catch (ConstraintViolationException co)
{
//check dates if more updated then replicate it with override
existDoc=(Documents)hdSession.load(Documents.class,doc.getDocumentid());
Date existDocDate= existDoc.getPublishdate();
Date duplicateDocDate = doc.getPublishdate();
if(duplicateDocDate.after(existDocDate))
{
hdSession.replicate(doc,ReplicationMode.OVERWRITE); m_updatedDocs.add(doc);
}
}
}
}
I have 2 questions:
First,
I see that I need to use session.flush after the : hdSession.replicate(doc,ReplicationMode.EXCEPTION) in order to get the exception immediately, am I correct?
Second,
if I got an exception (meaning the document already exist in the hd db), I am tring to load the document that exist in the hd DB for comparing dates, by:hdSession.load(Documents.class,doc.getDocumentid()) but from what I see this returns me the document that I have just tried to insert from the cd(by the replicate that failed). why?
is it in the session although the replicate didn't work?
am I suppose to open & close new session for every record?
|