Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IF construction in Hibernate

I'm using the construction "if" in HSQL:

String q = "SELECT id, name, " +
                "IF (ABS(name) > 0, LPAD(ABS(name), 4, '0'), name) AS tord " +
                "FROM table where city= " + cityId + " order by tord";

    Query query = session.createSQLQuery(q);
    List<Object[]> list = query.list();
    session.getTransaction().commit();
    session.close();

And now i want to refactor this piece of code with HQL. How can i do this? Thanks.

like image 403
evm Avatar asked Feb 12 '11 12:02

evm


1 Answers

Option 1.

Replace IF with CASE:

(case when ABS(name) > 0 then LPAD(ABS(name), 4, '0' else name end) AS tord

See HQL documentation for details.

Option 2.

HQL supports native functions. If you encapsulate calculations in custom SQL function you can write something like:

select t.*, paddNumber(t.name, 4) as tord from TableEntity t 
where t.city = :city order by tord

Have no environment to check but think each result record will be represented as Object[]. Where first element will contain your entity and second will contain tord.

Option 3.

If possible, rewrite application logic. There are different ways to add required padding to field 'name' before saving record. This will remove unnecessary calculation in DB during sorting.

like image 101
Vladimir Korolev Avatar answered Oct 01 '22 13:10

Vladimir Korolev