javahibernate

Hibernate find an existing object in db


Simple question here:

If I've got an object with initialized and uninitialized values in it. Is there an easy way to find in my db all the Entities that fit this one with hibernate? (without listing and checking every variable of the object)

Example:

I got this class:

public class User {
    private int id;
    private String name;
    private String email;
    private boolean activ;
}

I would like to be able to do that:

User user1 = new User();
user.setActive() = true;

User user2 = new User();
user.setActive(true);
user.setName("petter")

listUser1 = findAllUser(user1);
listUser2 = findAllUser(user2);

Here listUser1 will contain all the active users and listUser2 will contain all the active user that are named petter.

Thanks guys!

Edit/Solution

So my here is my code (I used a class which is similar at the one of my example). It work just fine but the problem is that according to Eclipse: "The method createCriteria(Class) from the type SharedSessionContract is deprecated"...

public static List<Personne> findAllPersonne(Personne personne) {
    List<Personne> listPersonne;
    
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("testhibernate0");
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    
    Session session = entityManager.unwrap(Session.class);

    Example personneExample = Example.create(personne);
    Criteria criteria = session.createCriteria(Personne.class).add(personneExample);

    listPersonne = criteria.list();

    entityManager.close();
    return listPersonne;
}  

So .. How could I do that in a better way? I've looked into CriteriaQuery but I can't find how to use it with an example.


Solution

  • Yes it exists : the key word for google is "query by exemple" or "qbe". https://dzone.com/articles/hibernate-query-example-qbe