例外:密钥'PRIMARY'的重复条目'1- \ x01'

时间:2014-04-04 14:02:21

标签: java hibernate hibernate-mapping

我在可嵌入的班级newEntity1中有一个名为Leaverequest的实体。我在实体类中使用Collectionofelements但是我得到以下异常。有人可以解释一下这意味着什么吗?

异常

Caused by: java.sql.BatchUpdateException: Duplicate entry '1-\x01' for key 'PRIMARY'
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2028)
    at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1451)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
    ... 8 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1-\x01' for key 'PRIMARY'

实体:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.treamis.entity;

import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.hibernate.annotations.CollectionOfElements;

/**
 *
 * @author hyva
 */
@Entity
public class NewEntity1 implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @CollectionOfElements
    private Set<LeaveAppliedDetails> leaveAppliedDetails = new LinkedHashSet<LeaveAppliedDetails>();

    @Override
    public String toString() {
        return "com.treamis.entity.NewEntity1[ id=" + id + " ]";
    }

    public Set<LeaveAppliedDetails> getLeaveAppliedDetails() {
        return leaveAppliedDetails;
    }

    public void setLeaveAppliedDetails(Set<LeaveAppliedDetails> leaveAppliedDetails) {
        this.leaveAppliedDetails = leaveAppliedDetails;
    }

    public boolean addLeaveAppliedDetails(LeaveAppliedDetails e) {
        return leaveAppliedDetails.add(e);
    }

}

测试人员类:

NewEntity1 newEntity = new NewEntity1();

LeaveAppliedDetails lad=new LeaveAppliedDetails();
lad.setHalfDay(true);
newEntity.addLeaveAppliedDetails(lad);
LeaveAppliedDetails lad1=new LeaveAppliedDetails();
lad1.setHalfDay(true);
newEntity.addLeaveAppliedDetails(lad1);
Session s=HibernateUtil.getSessionFactory().openSession();
s.save(newEntity);
s.beginTransaction().commit(); 

1 个答案:

答案 0 :(得分:0)

In these docs您可以阅读以下内容:

  

注意

     

我们建议您从中迁移   @ org.hibernate.annotations.CollectionOfElements到新的   @ElementCollection注释。

我建议您将注释@CollectionOfElements更改为@ElementCollection,然后逐步完成上一节。

我认为问题是,您尝试在LeaveAppliedDetails类中添加NewEntity1的新对象,这些对象在数据库中尚不存在(没有主键已知) 。所以尽量保存&amp;在将新LeaveAppliedDetails对象添加到NewEntity1之前检索它们。