我在插入/更新中有一个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
用户代码:bob
byteXmt:100
dummyKey:2
userEntity:null
用户代码: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”记录
如何使用相同的记录?
最佳答案
我认为您需要做的是首先保留User对象。您创建了User实体并将其与会话实体相关联,但是我敢打赌,通过对象图的另一条路径也到达了User。这是保存新对象的第二次尝试。