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

@Table(name = "CONTACT")
Public class Contact {

    private long id;
    private String lastname;
    private String firstname;
    private String language;

    //getters & setters;

In your DAO class add the following code:

Method in your DAO class

public Contact searchContact(Contact contact) {
    return (Contact) sessionFactory.getCurrentSession().createCriteria(Contact.class).add(Example.create(contact).ignoreCase().enableLike(MatchMode.ANYWHERE)).uniqueResult();

Unit test

public void testSearchContact() {
    Contact contact = new Contact();
    Contact c = contactDao.searchContact(contact);

    assertEquals(c.getId(), 123);
    assertEquals(c.getLastname(), "Hinoul");

Add comment

Leave a Reply

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

Tag Cloud