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

I am trying to insert a class Memberas follows, but it returns below the exception.

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

the code

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

....
session.save(member);

The objects

@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;

    .....
}
+4
source share
6 answers

Check if an empty row is added to the table that maps to Member. Because Duplicate entry '' for key 'UK_7pn834d04yft1rkvpqf0viuyc'= you are trying to add the same value a second time.

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

Since you marked this as unique, perhaps you are trying to add emailas an empty string a second time, but you have a restriction on this, saying that you cannot add the same value.

+3
source

, Hibernate, . hbm2ddl.auto=create

/, @ForeignKey , ( ) . .

mysql INFORMATION_SCHEMA.

+1

, "" "" "deleted = false, insertable = false".

+1

, , (, , ). Integer . , , .

+1

Check if the restrictions added for hibernation are related to the db used.

0
source

I am not 100% sure, but I suspect that using DEFAULT in the id position instead of automatic auto-communication see link

0
source

Source: https://habr.com/ru/post/1598561/


All Articles