Antoine Grenard
Antoine Grenard

Reputation: 1892

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.

Thx guys !

Edit/Solution

So my here is my code (i used a class wich 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.

Upvotes: 3

Views: 15241

Answers (2)

Brandon McKenzie
Brandon McKenzie

Reputation: 1685

In general, if an entity instance is already in your Persistence context, you can find it by primary key with EntityManager.find. Otherwise, you can pick up a result from your database by way of JPQL or native querying.

For your particular use case, it sounds like a querying solution would be the best fit; use one of the linked query creation methods from your entity, then use the Query.getResultList() method to pick up a list of objects that match the query criteria.

QueryByExample is also a good and valid solution, as Mr_Thorynque indicates, but as the article he linked mentions, that functionality is specific to certain JPA providers (Hibernate among them) and not JPA provider agnostic.

Upvotes: 0

Mr_Thorynque
Mr_Thorynque

Reputation: 2002

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

Upvotes: 4

Related Questions