1


I'm facing a little problem with Hibernate. I have a class:

public class Clazz{
   private int idClazz;
   //getters & setters...
}

It is correctly mapped within Hibernate. I want to select all the lines of this class in the database, but I want the idClazz field to be 100 * the ID in the databse.

So I make a small HQL query:

daoObject.createQuery("select 100*idClazz as idClazz from Clazz");

When I print the list of objects from this query, I still get the "normal" IDs. What I am doing wrong?

Thanks for your help!
(ps: of course this is an simplified situation, I don't exactly want to do this)

toni07
  • 356
  • 7
  • 20
  • Are you looking for something like this? [Computed Columns](http://stackoverflow.com/questions/2986318/calculated-property-with-jpa-hibernate) – Bastian Voigt Dec 03 '13 at 15:48
  • Thanks for your time, but I dont't want the field to be calculated every time (sometimes I want it to be the "real" value), that's why I make an HQL query. – toni07 Dec 03 '13 at 16:04

2 Answers2

1

I don't know about changing the value of the ID column on query, you could end up with that persisted back, I'd have to run a test to see.

Seems to me it would be safer to have a transient field calculated at load time like this:

@Transient
private int IDMulled;

@PostLoad
public void onPostLoad() {
    this.IDMulled = idClazz * 100;
}

Alternatively, since I don't think what you want to do is legal in JPQL, you could do a native SQL query like this:

session.createSQLQuery("Select (idClazz * 100) as result From Clazz");
WPrecht
  • 1,340
  • 1
  • 17
  • 29
  • Actually that's the idea I have set up: I calculate the * 100 thing directly in my code, but I thought you could do it simply in HQL. An important thing: not any of my Clazz instances are to be peristed back. – toni07 Dec 03 '13 at 16:08
  • Looking at the BNF of JPQL, I don't think your query is legal even if it's not flagged as an error. – WPrecht Dec 03 '13 at 16:28
0

A field that has two different meanings depending on the context is not a good idea. It violates the Principle of least surprise, and will only help to confuse other developers or even yourself.

So use the @Formula annotation or the @Transient approach suggested by WPrecht. If the extra 4 bytes for an additional int field kills you, then you should not be using Hibernate anyway.

Bastian Voigt
  • 5,311
  • 6
  • 47
  • 65
  • 1
    My field is a rate, so it is < 1 in the database, sometimes I want to display it in percentage, sometimes not. Anyway I even don't really want to know if it is good or bad, I just want to know wheither it is possible, and how to acheive this. The question could be "how to get 35*field1 + 'toto' + 63*field2 in a String attribute?". I think you see the point, my question could be only technical. – toni07 Dec 03 '13 at 16:24