Reputation: 53
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
Upvotes: 1
Views: 5324
Reputation: 26094
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();
Upvotes: 1
Reputation: 39887
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.
Upvotes: 1