Reputation: 565
i've an MySQLIntegrityConstraintViolationException in insert/update.
here my entity
sessions entity:
@Entity
@Table
public class SessionEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private Integer dummyKey;
@ManyToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
@JoinColumn(name = "user",nullable = true,referencedColumnName = "id")
private UserEntity userEntity;
@Column(insertable=false, updatable=false)
private String userCode;
@Column
private Integer byteXmt;
--- setter and getter ---
}
users entity:
@Entity
@Table
public class UserEntity implements Serializable {
@Id
@Column
private String id;
@Column
private String firstName;
@Column
private String lastName;
--- setter and getter ---
}
At startup UserEntity has zero record and SessionEntity has 2 records:
dummyKey: 1
userEntity: null
userCode: bob
byteXmt: 100
dummyKey: 2
userEntity: null
userCode: bob
byteXmt: 200
I need push into UserEntity only a record and in SessionEntity the UserEntity reference:
List<SessionEntity> list = (List<SessionEntity>) em.createNamedQuery("getAllRecords").getResultList();
for (SessionEntity sessionEntity : list) {
String userCode = sessionEntity.getUserCode(); //"bob"
UserEntity user = usersDAO.load(userCode); // first time is null
if(user==null){
user = new UserEntity();
user.setId(userCode);
user.setFirstName(sessionEntity.getFirstName());
user.setLastName(sessionEntity.getSecondName());
}
assert sessionEntity.getUserEntity()==null;
sessionEntity.setUserEntity(user);
em.merge(sessionEntity);
}
the error is:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'bob ' for key 'PRIMARY'
i suppose inserts 2 times 'bob' record in UserEntity how could use same record?
Upvotes: 2
Views: 1586
Reputation: 2020
I think what you need to do is to persist the User object first. You create the User entity and associate it with the session entity, but I'm betting there is another path through the object graph that also gets to the User. And that is the second attempt to save the new object.
Upvotes: 1