Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composite primary key with not primitive attributes

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?

like image 480
svobol13 Avatar asked Nov 04 '22 12:11

svobol13


1 Answers

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;
}
like image 94
gkamal Avatar answered Nov 09 '22 07:11

gkamal