4

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?

Yurets
  • 3,999
  • 17
  • 54
  • 74
Cesar Sturion
  • 147
  • 1
  • 9
  • 1
    To help you get answered, please review http://stackoverflow.com/help/how-to-ask on how to ask a question – CCBlackburn Jan 21 '17 at 00:45
  • The same question: https://stackoverflow.com/questions/40720799/deprecated-createcriteria-method-in-hibernate-5 – faoxis Jul 31 '17 at 09:17

1 Answers1

8

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();
Naros
  • 19,928
  • 3
  • 41
  • 71