6

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?

Pete B.
  • 3,188
  • 6
  • 25
  • 38

2 Answers2

9

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.

Community
  • 1
  • 1
Koitoer
  • 18,778
  • 7
  • 63
  • 86
  • Hi @Koitoer, Suppose there are several rows with the same id. How do we query them using session.get without providing emailAddressId. It means I want all the entries with the same Id using session.get. – Rohit Mishra Mar 23 '17 at 10:47
  • 1
    to be honest I am not sure if that will be possible as you already defined a composed key in the jpa model, you could obviously use HQL to do that but that will create createQuery for session – Koitoer Mar 23 '17 at 15:53
  • Hibernate [documentation](https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#identifiers-composite) says "_Hibernate does allow composite identifiers to be defined without a "primary key class" via multiple @Id attributes._". Is there a way to get the entity without any `@EmbeddedId`? – dpelisek Apr 23 '20 at 09:51
  • I'm sure your solution works, but at this point I prefer to do a normal query. More simple. – Marco Sulla Oct 08 '21 at 09:02
1

In Hibernate yes (documentation):

MyJoinClass a = session.get(MyJoinClass.class, new MyJoinClass(100, 200));

Just make sure to have a constructor with all parts of the composite key (and don't forgot the default public constructor with no parameters):

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;

  public MyJoinClass() {}

  public MyJoinClass(long id, long emailAddressId) {
    this.id= id;
    this.emailAddressId= emailAddressId;
  }
}
dpelisek
  • 884
  • 3
  • 13
  • 22