How to find objects by attributes in Hibernate

H

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

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

    @Id
    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

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

Unit test

@Test
@Rollback(false)
public void testSearchContact() {
    Contact contact = new Contact();
    contact.setFirstname("lau");
    contact.setLanguage("nl");
    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

Categories