0

I need to save a list of objects of a table with composite primary key, I am doing as shown below. But I am getting an error Caused by: java.sql.BatchUpdateException: ORA-00001: unique constraint violated. But the items in the list are unique, what am I doing wrong.

// Table structure

@Entity
   @Table(name="COMP_PRIMARY")
   CompPrimaryObj{
   @Id
   @Column(name="KEY1")
   private String key1;

   @Id
  @Column(name="KEY2")
  private Long key2;
   }

// code in my service layer

List<CompPrimaryObj> compPrimaryObjList = new ArrayList<CompPrimaryObj>();
CompPrimaryObj obj1 = new CompPrimaryObj();
obj1.setKey1("key1");
obj1.setKey2(11111);
compPrimaryObjList.add(obj1);
CompPrimaryObj obj2 = new CompPrimaryObj();
obj2.setKey1("key2");
obj2.setKey2(222222);
compPrimaryObjList.add(obj2);
for(CompPrimaryObj compPrimaryObj:compPrimaryObjList){
   em.persist(compPrimaryObj);  // em stands for Entity manger instance
}
Greg
  • 147
  • 1
  • 5
  • 18

2 Answers2

1

When dealing with a composite primary key, you have two options. In each of them, you've got to create a new class to hold the fields that represent the PK:

Composite Primary Key:

@Entity 
@Table(name="COMP_PRIMARY")
@IdClass(CompPrimaryObjId.class)
public class CompPrimaryObj {
    @Id 
    @Column(name="KEY1")
    String key1;
    @Id 
    @Column(name="KEY2")
    Long key2;
    //...
}
public class CompPrimaryObjId{
    String key1;
    Long key2;
}

Or with Embedded Primary Keys:

@Embeddable
public class CompPrimaryObjId {       
    @Column(name="KEY1")
    private String key1;
    @Column(name="KEY2")
    private Long key2;
    // ...
   }
}

@Entity
@Table(name="COMP_PRIMARY")
public class CompPrimaryObj {
     @EmbeddedId
     private CompPrimaryObjId id;
     //....
}
Xavi López
  • 27,550
  • 11
  • 97
  • 161
  • Thanks for I will try to use the same. – Greg Oct 07 '11 at 15:04
  • I tried using the Idclass annotation but I still get the same unique constaint error, I believe there is an issue with how I am persisting the list of objects. – Greg Oct 07 '11 at 15:22
  • Have you tried with the `@Embeddable` and `@EmbeddedId` annotations? – Xavi López Oct 07 '11 at 18:27
  • Have you added the PK class `CompPrimaryObjId` to your mapped classes? Have you tried with the @Embeddable and @EmbeddedId annotations? – Xavi López Oct 07 '11 at 19:24
0

Recently I mapped @Many-To-Many with Composite primary keys. Look at this post I think it can give you all required information.

Mapping ManyToMany with composite Primary key and Annotation:

Community
  • 1
  • 1
danny.lesnik
  • 18,479
  • 29
  • 135
  • 200