6

I am new to Java and Hibernate. I've got problem with composite key. I am trying to do something like that:

@Entity
class A {
    @Id
    int id;
}

@Entity
class B {
    @Id
    int id;
}


@Entity
class C {
    @EmbeddedId
    C_PK c_pk;
}

@Embeddable
class C_PK {
    A a;
    B b;
}

When I perform

...
session.save(c);
...

Then exception is thrown that type of A and B cannot be inserted into database. Is it possible to somehow tell hibernate to don't save the A object but only the A id? Is my approach absolutely wrong and should I just use primitive data types at C_PK class?

Mat
  • 202,337
  • 40
  • 393
  • 406
svobol13
  • 1,842
  • 3
  • 25
  • 40

1 Answers1

2

You should put a @ManyToOne (or OneToOne) with join columns on the A and B references in C_PK.

@Embeddable
class C_PK {
    @ManyToOne
    A a;
    @ManyToOne
    B b;
}
gkamal
  • 20,777
  • 4
  • 60
  • 57
  • 1
    Please read section 2.2.3.2 - http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#d0e2177. "While not supported in JPA, Hibernate lets you place your association directly in the embedded id component (instead of having to use the @MapsId annotation)." – gkamal Oct 16 '11 at 11:35
  • Sorry, I was wrong, it really looked improper. I'll revert my unjust vote once you edit the answer. – MaDa Oct 16 '11 at 14:06
  • `org.springframework.beans.ConversionNotSupportedException:` – Bawantha Oct 21 '21 at 05:42