Kevin Cruijssen
Kevin Cruijssen

Reputation: 9326

Convert HQL query in the form of "select foo from Foo foo, Bar bar where ..." to Criteria query

In our (ancient) project, we use loads of select queries with HQL on Hibernate version 3.5.6-Final. Because Hibernate will do an auto-commit, because it doesn't know they are select queries, I'm in the process of rewriting all HQL select queries to Hibernate Criteria queries so it won't do in-between commits when we don't want it yet. This is pretty straight-forward in most cases, but I'm currently looking at a query like this, and I'm not sure how to transform it:

Query query = session.createQuery("select municapilityStreet"
  + " from MunicapilityStreet munStreet, Street street"
  + " where munStreet.id = street.MunicapilityStreet.id"
  + " and street.id = :streetId");
query.setParameter(":streetId", streetId);
MunicapilityStreet result = (MunicapilityStreet) query.uniqueResult();
return result;

Here what I have thus far in the process of transforming it:

Criteria criteria = session.createCriteria(MunicapilityStreet.class);

// No idea what to set here to only get the "municapilityStreet" as result
criteria.setProjection(??);

// I'm not sure if this is correct. With a criteria on a single table it would have been simply "Id".
// Both tables have the column-name Id, and I'm not sure how to differentiate between them.
criteria.add(Restrictions.eq("Street.Id", streetId));

MunicapilityStreet result = (MunicapilityStreet) criteria.uniqueResult();
return result;

Maybe I should create a different question for each, but converting the above HQL query to a Criteria has three points I'm not sure about how to do:

  1. How to do a select with multiple tables (the from MunicapilityStreet munStreet, Street street part)?
  2. How to have a projection to only return a single table of the two (the select municapilityStreet part)?
  3. How to have an equal-Restriction on a column name of one table, even though both tables have the same column-name (the and street.id = :streetId part)?

Upvotes: 0

Views: 92

Answers (1)

Curiosa Globunznik
Curiosa Globunznik

Reputation: 3205

I do oppose the rewrite approach, I hope I'm not impolite doing so.

Hibernate allows to control commits (autocommit is by default off), and what you're experiencing are Entitymanager-flushes, they are auto by default and can be disabled too. And, finally, I think, there is no difference if you're running HQL or criteria queries, same machinery underneath.

Upvotes: 1

Related Questions