Hibernate 5 - createCriteria deprecated

ぐ巨炮叔叔 提交于 2020-02-22 05:39:29

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/41773336/hibernate-5-createcriteria-deprecated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!