我在插入/更新中有一个MySQLIntegrityConstraintViolationException。
这是我的实体
会话实体:
@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 ---
}
用户实体:
@Entity
@Table
public class UserEntity implements Serializable {
@Id
@Column
private String id;
@Column
private String firstName;
@Column
private String lastName;
--- setter and getter ---
}
启动时,UserEntity的记录为零,SessionEntity有2条记录:
dummyKey:1
userEntity:null
userCode:bob
byteXmt:100
dummyKey:2
userEntity:null
userCode:bob
byteXmt:200
我只需要将一个记录推入UserEntity,并在SessionEntity中推送UserEntity引用:
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);
}
错误是:
引起: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 键'PRIMARY'重复输入'bob'
我想在UserEntity中插入2次'bob'记录 如何使用相同的记录?
答案 0 :(得分:1)
我认为您需要做的是先保留User对象。您创建用户实体并将其与会话实体关联,但我打赌通过对象图还有另一条路径也可以访问用户。这是保存新对象的第二次尝试。