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;
.....
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With