Reputation: 31
I added unique constraint annotation but still I can insert duplicate entry.
@Entity
@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"firstName", "LastName"})})
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String LastName;
//getter and setter and no-arg constructor
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Student student1 = new Student("alireza", "rayani");
Student student2 = new Student("alireza", "rayani");
session.save(student1);
session.save(student2);
session.getTransaction().commit();
Upvotes: 0
Views: 2074
Reputation: 31
Finally ,I found out the problem ,I changed dialect from
properties.put(Environment.DIALECT,"org.hibernate.dialect.MySQL5Dialect");
to
properties.put(Environment.DIALECT, "org.hibernate.dialect.MySQL57Dialect");
Upvotes: 3
Reputation: 2947
The schema for your database is generated by Hibernate? @UniqueConstraint is only used to generate the schema. If the database already exists, you should execute the alter table
on it to add the constraint.
Upvotes: 0