Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate returns com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry

I am trying to insert Member class as following but it returns below exception.

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 
Duplicate entry '' for key 'UK_7pn834d04yft1rkvpqf0viuyc'

Code

Member member = new Member(email, encodedPassword,
                    "USER", false, firstName,
                    lastName);

....
session.save(member);

Entities

@Entity
public class Member {
    @Id
    @Column(name = "username", nullable = false, unique = true)
    private String email;
    @Column(nullable = false)
    private String password;
    @Column(nullable=false)
    private String authority;
    @Column(nullable = false)
    private boolean enabled;
    @Column(nullable = false)
    String fname;
    @Column(nullable = false)
    String lname;
    @OneToMany
    List<Product> products = new ArrayList<Product>();
    @OneToMany(mappedBy = "requester")
    private Set<Friendship> friendRequests = new HashSet<Friendship>();
    @OneToMany(mappedBy = "friend")
    private Set<Friendship> friends= new HashSet<Friendship>();
    .....
}



 @Entity
public class Friendship implements Serializable {

    private static final long serialVersionUID = -12799066578787745989L;
    @Id
    @ManyToOne
    @JoinColumn(referencedColumnName = "username")
    Member requester;
    @Id
    @ManyToOne
    @JoinColumn(referencedColumnName = "username")
    Member friend;
    @Temporal(javax.persistence.TemporalType.DATE)
    Date date;
    @Column(nullable = false)
    boolean active;

    .....
}
like image 617
Daniel Newtown Avatar asked Mar 15 '23 09:03

Daniel Newtown


2 Answers

Check if you are adding empty string to table that is mapped to Member. Since Duplicate entry '' for key 'UK_7pn834d04yft1rkvpqf0viuyc' = you are trying to add the same value second time.

Look at this:
@Column(name = "username", nullable = false, unique = true) private String email;

Since you have marked this as unique propably you are trying to add email as empty string second time but you have a constraint on it saying you cannot add the same value.

like image 124
Paweł Głowacz Avatar answered Apr 06 '23 11:04

Paweł Głowacz


It looks like the keys are generated by Hibernate, e.g. with hbm2ddl.auto=create

If this is a development/test environment, you can add @ForeignKey annotations to your model and see which key (related to which property) is being violated after regenerating the tables. It's worth writing a few extra lines for the ease of debugging.

In a production environment, you can track the key from mysql INFORMATION_SCHEMA tables.

like image 25
Turan Yüksel Avatar answered Apr 06 '23 10:04

Turan Yüksel