0

I have an entity with composite id , I'm using hibernate's Multiple id properties without identifier type , like so :

@Entity
class MyEntity  implements Serializable {

   @Id
   private Long id1;

   @Id
   private Long id2;

   //... Getters , setters , hashcode , equals ...
}

The problem is that in my Database: id1 = 1 , id2 = 2

And if I want to add a row with : id1 = 2 , id2 = 2

I get an error ConstraintViolationException: Duplicate entry '2' for key 'id2'

I'm using hibernate 4.1.7, The documentation link : http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#mapping-declaration-id

Update

I'm talking about a Hibernate-specific solution: Map multiple properties as @Id properties without declaring an external class to be the identifier type

Afsun Khammadli
  • 2,048
  • 4
  • 18
  • 28
Mohamed Ramrami
  • 12,026
  • 4
  • 33
  • 49

2 Answers2

0

Use EmbeddedId. Please refer this.

kondu
  • 410
  • 3
  • 11
  • Thanks , I know that it work with EmbeddedId. But in Hibernate docs there is a section '5.1.2.1.2.Multiple id properties without identifier type' , where they say that it work without EmbeddedId , and you can check the code snippet they give – Mohamed Ramrami May 18 '15 at 10:06
0

It's very possible the problem is not your code, but your db schema. Without knowing what DBMS you're using and the constraints/indexes on the table for MyEntity, it's impossible to say for sure. However my guess is that you have something like this:

CREATE UNIQUE INDEX ON my_entity (id1);
CREATE UNIQUE INDEX ON my_entity (id2);

which requires that each column independently contains only unique values, when you really want something like this:

CREATE UNIQUE INDEX ON my_entity (id1, id2);

which allows each column to contain duplicates of the same value, as long as the combination of both columns is unique.

zacronos
  • 1,487
  • 1
  • 12
  • 13