Reputation: 459
I am facing a strange problem in Hibernate. Operating in a multithreaded env, when trying to insert into one of the tables, getting duplicate entries in table. Only the primary key is different, rest all other fields are getting exactly duplicate.
Using Hibernate + Oracle and using Spring - HibernateTemplate object.
Here's the relevant portion of my my BO class and below given code to save the object. Not using any transient fields.
Have checked other posts related to this, but none of them addresses the root cause of the problem. I don't want to introduce any constraints/unique indexes on db table.
@Entity
@Table(name="ADIRECIPIENTINTERACTION")
@Lazy(value = true)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@GenericGenerator(name="recipientInteractionSeq", strategy = "native", parameters =
{ @Parameter(name="sequence", value="SEQiRecipientInteractId")})
public class RecipientInteractionBO extends BusinessObject{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "recipientInteractionSeq", strategy = GenerationType.AUTO)
@Column(name="IRECIPIENTINTERACTIONID")
private long lId; ....
And here's the Code used to save the BO.
-----------------------------------------------------
RecipientInteractionBO recInt = (RecipientInteractionBO) objectPS
.getUniqueResult(detachedCriteria);
if (recInt == null) {
recInt = new RecipientInteractionBO();
....
hibernateTemplateObj.insertObject(recInt);
} else {
...
hibernateTemplateObj.saveOrUpdate(recInt);
}
Please let me know if any other details are required.
Upvotes: 0
Views: 1405
Reputation: 9102
Check your data persistence code for possible race conditions for multiple threads. You are checking for the existence of the RecipientInteractionBO
which is possibly querying from database. If two threads are running simultaneously, both check for it's existence, since for both it's not there both persist the new entity. You might need to use synchronization to make the process of checking and inserting/updating to be done only for one thread at a single time.
Upvotes: 1