1

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

Haseena
  • 53
  • 1
  • 7

2 Answers2

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