Laurent Hinoul

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.” - John F. Woods

How to find objects by attributes in Hibernate

What if you have an object without ID. How do you know if that object already exists in the database?

Let’s say that you have a contact object with the next data:

  • id: unknown
  • lastname: unknown
  • firstname: lau
  • language: nl

In the database, the data is like:

  • id: 123
  • lastname: Hinoul
  • firstname: Laurent
  • language: NL

As you can see, we don’t have all the data in our object. How do you precisely get that record from hibernate by your current object? See the code below:

Contact model class

In your DAO class add the following code:

Method in your DAO class

Unit test

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: