Hibernate NonUniqueObjectException:具有相同标识符

时间:2018-02-03 15:04:12

标签: java hibernate

Hello Friends:我第二次收到错误,我试图将相同的票证和警察实例保存到DB,这是我的代码pojo类Cop和DaoCop以及main方法。票证及其Dao类与警察类的结构相同。这个想法是警察可以创建许多票,一张票只能由一个警察创建。因此,当我尝试将我们的数据库中已存在的同一个警察与我得到的许多故障和非独特异常的休眠错误相关联时。

@Entity
@Table(name="cop")
@NamedQueries(
    {
       @NamedQuery
       (
               name = "findPolicierByMatricule",
               query = "from Policier pol where pol.numMatricule = 
               :matricule"

       )
    }
 )
public class Cop
{
  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = 
          "policier_generator")
  @SequenceGenerator(name="policier_generator", sequenceName = 
         "policier_seq", allocationSize=1)
  @Column(name = "idCop")
  private int idCop;

  @Column(name="numMatricule")
  private int numMatricule;

  @Column(name="prenom")
  private String prenom;

  @Column(name="nom")
  private String nom;

  @OneToMany(fetch = FetchType.EAGER, mappedBy = "cop", cascade =
     {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, 
      CascadeType.DETACH})
  private List<Ticket> listTickets;

  .....
}

  public class DaoCop
  {
    @Override
    public Policier findById(Object matricule)
    {
          openCurrentSessionwithTransaction(); //Get the session and 
                Begin transaction
          Query query = 
          getCurrentSession().getNamedQuery("findPolicierByMatricule");
          query.setParameter("matricule", matricule);
          Cop cop;
          List<Cop> list = (List<Cop>) query.getResultList();
          if(list == null || list.isEmpty())
          {
               cop = null;

           }
         else
         {
            cop = list.get(0);
         }
         closeCurrentSessionwithTransaction(); //Commit and Close the 
           //session
        return cop;
   }
 }

 public static void main(String[] args)
 {
    daoTicket = DaoFactory.getDaoTicket();
    daoCop = DaoFactory.getDaoCop();
    Cop cop;
    Ticket ticket;
    Cop temp = (Cop) daoCop.findById(numMatricule);
    if(temp == null) //If the cop with the nummatricule does not exist          
    {
      cop = new Cop(numMatricule, prenom, nom);//in our DB we create an 
                  //new one
    }
    else
    {
      cop = temp; //else we use the one arleary exit.
    }
    ticket = new Ticket("21-21-18",51.02);
    //Link Objects in Memeroy

    cop.add(ticket);

   //Save Objects in DB
   daoTicket.create(ticket);
 }

2 个答案:

答案 0 :(得分:0)

您应该为克隆对象创建一个新ID。你能为其他部分尝试这个:

else
{
  Cop copCopy = temp.createCopyWithNoId()
  DaoCop.add(copCopy)
  cop = copCopy; //else we use the one arleary exit.
}

答案 1 :(得分:0)

解决方案是Cop Class中的CascadeType,所以我完全删除它并且错误消失了。