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

6
  • What about the relative code ?? Commented Aug 14, 2013 at 9:53
  • Do you have your insert methods synchronized? Commented Aug 14, 2013 at 9: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 Commented Aug 14, 2013 at 9:58
  • @JunedAhsan no insert methods not synchronized Commented Aug 14, 2013 at 9:59
  • before inserting entries you can check their uniqueness by using Map with the existing entries in dataBase Commented Aug 14, 2013 at 10:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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();

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.