Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Hibernate Get with Multi-Column Primary Key

Say I have a class that looks like this:

public class MyClass {
  @Id
  @Column(name = "ID")
  private long Id;
}

I can use a hibernate session to do a get or load on the class like this:

MyClass a = (MyClass)session.get(MyClass.class, new Long(100));

However, assume I have a class with multiple columns as the primary key:

public MyJoinClass implements Serializable {
  private static final long serialVersionUID = -5L;
  @Id
  @Column(name = "ID")
  private long id;

  @Id
  @Column(name = "EMAIL_ADDRESS_ID")
  private long emailAddressId;
}

Is it possible to use get or load with such a class?

like image 331
Pete B. Avatar asked Apr 28 '15 17:04

Pete B.


People also ask

Can a primary key be based on multiple columns?

The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).


1 Answers

Try to use and @IdClass or @EmbeddedId

public MyJoinClass implements Serializable {
  private static final long serialVersionUID = -5L;

  @EmbeddedId
  private MyJoinClassKey key;
}

public MyJoinClassKey implements Serializable{

  @Column(name = "ID")
  private long id;

  @Column(name = "EMAIL_ADDRESS_ID")
  private long emailAddressId;
}

Then use

MyJoinClass a = (MyJoinClass )session.get(MyJoinClass .class, new MyJoinClassKey (1, "email"));

Take a look at this question, this is broadly explained. Basically hibernate have a mechanism for compound keys.

like image 138
Koitoer Avatar answered Sep 19 '22 08:09

Koitoer