Hi All!
How can I update on duplicate key using hibernate?
Funny thing is, I dont ever recall getting this error last week. I do remember trying to place indecies on some tables.
Here is a table I am writing to:
DROP TABLE IF EXISTS `brokerage`.`SecuMaster`;
CREATE TABLE `brokerage`.`SecuMaster` (
`cusip` char(9) NOT NULL,
`date` char(8) NOT NULL,
`price` decimal(16,2) NOT NULL,
`fundcode` varchar(55) default NULL,
`description` varchar(255) default NULL,
`modifydate` varchar(8) NOT NULL,
`timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY USING BTREE (`cusip`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Here is my code:
// We create a crazy loop to skip the first and last rows.
for (int i = 1; i < hash.size() - 1; i++) {
String CUSIP = hash.get("Line" + i).substring(6, 15);
String Date = hash.get("Line" + i).substring(22, 30);
String FUNDCODE = hash.get("Line" +i).substring(15, 22);
// Date newDate = new SimpleDateFormat("yyyyMMdd").parse(Date);
// String fDate = new
// SimpleDateFormat("yyyy-MM-dd").format(newDate);
String Price = hash.get("Line" + i).substring(31, 39);
BigDecimal d = new BigDecimal(Price).setScale(2,
BigDecimal.ROUND_CEILING);
System.out.println("Inserting...");
System.out.println(CUSIP + " " + Date + " "
+ d.divide(navprecision).setScale(2, BigDecimal.ROUND_CEILING)+" FUND CODE:"+FUNDCODE);
SecuMaster security = new SecuMaster();
security.setCusip(CUSIP);
security.setDate(Date);
security.setPrice(d.divide(navprecision));
security.setFundcode(FUNDCODE);
security.setModifydate(lastModifiedDate);
try{
session = HibernateUtil.getSessionFactory()
.getCurrentSession();
tx = session.beginTransaction();
session.saveOrUpdate(security);
}catch(HibernateException e){
e.printStackTrace();
log.error(e.getMessage());
tx.rollback();
}
// This closes the session.
// If you call it again, you'll get an exception
tx.commit();
parsed=true;
}
return parsed;
}
This was working fine, but now I get: java.sql.BatchUpdateException: Duplicate entry
Should I change my table, maybe add a int as primary key, instead of the cusip on this table?
Not sure why I get this error. I am using saveOrUpdate, so shouldn't that update the anyway?