I am updating the record with multiple entries in the db at a time.when i try to create another multiple records, duplicate entries are saved in DB.how to prevent records from duplicates entry using hibernate.i want to restrict 2 or more column value should not equal as before
Asked
Active
Viewed 5,159 times
1
-
What about the relative code ?? – Suresh Atta Aug 14 '13 at 09:53
-
Do you have your insert methods synchronized? – Juned Ahsan Aug 14 '13 at 09:53
-
@sureshatta for one market id, i m creating 4 entries per month like 1/08/2013 to 31/08/2013.when i select same market id with other dates like 15/08/2013 to 18/09/2013 duplicates entries are allowed from the previous entry – Haseena Aug 14 '13 at 09:58
-
@JunedAhsan no insert methods not synchronized – Haseena Aug 14 '13 at 09:59
-
before inserting entries you can check their uniqueness by using `Map` with the existing entries in dataBase – aizaz Aug 14 '13 at 10:05
-
Did you consider constructing composite primary key with unique columns for your table? – Siva Aug 14 '13 at 10:23
2 Answers
1
Defining a primary key, or at least a unique constraint, on the table, is the surest way to avoid duplicates. Then your code will throw some useful errors for you to handle transactions properly.

Adeel Ansari
- 39,541
- 12
- 93
- 133
1
Define your entity object with Unique Constraints
@Entity
@Table(name="user_group",
uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id", "group_id"})})
public class UserGroup implements Serializable
{
User user //This is user model
Group group // This is Group model
// Other fields
// setter and getter methods.
}
Save the objects within a transaction
Session session = sessionFactory().openSession();
session.beginTransaction();
session.saveOrUpdate(listOfuserGroup);
session.getTransaction().commit();

Dmitry Ginzburg
- 7,391
- 2
- 37
- 48

Prabhakaran Ramaswamy
- 25,706
- 10
- 57
- 64
-
my primary key ids are unique...data what i am inserting in db is same except id, and marketcode.i tried using uniqueconstraint..but no luck – Haseena Aug 14 '13 at 11:33