-1

is it possible to define two keys in hibernate, so i can hit the first-level-cache with both keys?

@Entity
class User {
  @Id
  int id;

  @Id
  String username;
}

so session.get(User.class, 'harry') is the same as session.get(User.class, 1)

is it possible?

wutzebaer
  • 14,365
  • 19
  • 99
  • 170

2 Answers2

2

You might be interested in this feature of 4.1

You can in fact hit the first level cache using the @Id or the @NaturalId. Just make sure you are using 4.1.x.

Alex Barnes
  • 7,174
  • 1
  • 30
  • 50
  • hi thanks thats the same as in Firo's link, works great, fortunately i had already upgraded my hibernate version – wutzebaer Jun 12 '12 at 07:39
  • They're very different links. @firos link is referring to a blog post in 2009 and talks about simply not checking the second level cache for expiration - this will not hit the session cache. The link I've posted refers to new functionality which will hit the session cache when you use the natural id. – Alex Barnes Jun 12 '12 at 12:20
  • hm i tried the example of Firo, but when querying for the natural id with criteria hibernate recommends to use "session.byNaturalId" so i used this. are there any other differences? – wutzebaer Jun 12 '12 at 20:30
  • I'm not quite sure what you're asking. Using session.byNaturalId will ensure that you hit the first level cache. Is that not what you wanted? Using a Query will never hit the first level cache. – Alex Barnes Jun 12 '12 at 21:02
  • hi, yes everything is fine now, thats exactly what i wanted. i just wanted to tell you that i already came to the soulution with "session.byNaturalId" because of hibernate's log message when querying for it. thanks – wutzebaer Jun 13 '12 at 07:43
1

short answer: no

long answer: there is the @NaturalId annotation which does a little, see here, but there is only ever one id for hibernate. you could implement your own using a dictionary.

Firo
  • 30,626
  • 4
  • 55
  • 94