Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are positional parameters deprecated in Hibernate 5.3.2?

We are migratiing from Hibernate 3 to Hibernate 5.3 ,We have used positional parameters in HQL, I see some posts on Hibernate support saying that positional parameters are no longer supported in Hibernate 5. And should be replaced with named parameters ?

Can some one confirm this ?

And if possible please let me know what all are deprecated from Hibernate 3 ?

Thanks in Advance.

like image 953
Harsha vardhan yadlapalli Avatar asked Oct 17 '22 11:10

Harsha vardhan yadlapalli


1 Answers

Support for legacy-style query parameter ('?') declarations in HQL/JPQL queries has been removed. This feature has been deprecated since Hibernate 4.1 and finally removed in 5.3 version.

Therefore, the following query declaration is not valid:

Query<Product> query = OBDal.getInstance().getSession()
    .createQuery("from Product as p where p.name = ? and p.stocked = ?", Product.class);
query.setParameter(0, "Ale Beer");
query.setParameter(1, true);

Please note that although the previous code compiles successfully, it will be failing at runtime. To make the previous query work fine it must use named parameters:

Query<Product> query = OBDal.getInstance().getSession()
    .createQuery("from Product as p where p.name = :name and p.stocked = :isStocked", Product.class);
query.setParameter("name", "Ale Beer");
query.setParameter("isStocked", true);

In case of using OBQuery it is recommended to neither use positional parameters:

OBQuery<Product> obQuery = OBDal.getInstance().createQuery(Product.class,
    "as p where p.name = ? and p.stocked = ?");
List<Object> parameters = new ArrayList<>(2);
parameters.add("Ale Beer");
parameters.add(true);
obQuery.setParameters(parameters);

Note that the previous query will not fail due to an internal mechanism that converts the positional parameters into named parameters. In any case, it is recommended to use named parameters instead and for this reason the OBQuery.setParameters() method is deprecated since 3.0PR18Q3 release.

OBQuery provides the setNamedParameters method to provide a map containing the named parameters with their respective values:

OBQuery<Product> obQuery = OBDal.getInstance().createQuery(Product.class,
    "as p where p.name = :name and p.stocked = :isStocked");
Map<String, Object> parameters = new HashMap<>(2);
parameters.put("name", "Ale Beer");
parameters.put("isStocked", true);
obQuery.setNamedParameters(parameters);

Or alternatively:

OBQuery<Product> obQuery = OBDal.getInstance().createQuery(Product.class,
    "as p where p.name = :name and p.stocked = :isStocked");
obQuery.setNamedParameter("name", "Ale Beer");
obQuery.setNamedParameter("isStocked", true);

For more help on migration to Hibernate 5.3: http://wiki.openbravo.com/wiki/Hibernate_5.3_Migration_Guide

like image 101
Shubham Kadlag Avatar answered Oct 21 '22 03:10

Shubham Kadlag