Cesar Sturion
Cesar Sturion

Reputation: 147

Hibernate 5 - createCriteria deprecated

I need a help to migrate the code with createCriteria for Hibernate 5, the code is this below:

public Curso comDadosIguais(Curso curso) {
    return (Curso) this.session.createCriteria(Curso.class)
            .add(Restrictions.eq("codigo", curso.getCodigo()))
            .uniqueResult();
}

Could you help me?

Upvotes: 4

Views: 9333

Answers (1)

Naros
Naros

Reputation: 21113

There are a number of options you can exercise to migrate from the deprecated Hibernate Criteria API, these are just a few that immediately come to mind:

  • HQL / JPQL
  • Named query
  • JPA Criteria API

From a HQL / JPQL perspective, you could rewrite your query as a string:

Curso result = session.createQuery( "FROM Curso WHERE codigo = :codigo" )
     .setParameter( "codigo", curso.getCodigo() )
     .uniqueResult();

You can also use a @NamedQuery which is basically an annotation you apply to an entity or a package where you supply a HQL query much like you see above, specifying a placeholder for your query parameters much in the same way and then supplying those parameters are runtime when you execute the query, like:

Curso result = session.createNamedQuery( "Curso.findByCodigo" )
     .setParameter( "codigo", curso.getCodigo() )
     .uniqueResult();

And finally, you can also consider the JPA Criteria API. This is available if you're using a JPA EntityManager rather than a Hibernate Session.

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Curso> query = cb.createQuery( Curso.class );
Root<Curso> root = query.from( Curso.class );

query.select( root )
     .where( cb.eq( root.get( "codigo" ), curso.getCodigo() ) );

Curso result = entityManager.createQuery( query ).getSingleResult();

Upvotes: 8

Related Questions