Wednesday, December 12, 2007

JPA - Column annotation tip

Being an Oracle guy, I always have enjoyed getting into the guts of the SQL language. Recently I have been using JPA quite a bit recently and was frustrated by a particular problem. I needed to include a column that was generated off of other columns. For instance:

  1. SELECT a, b, a+b FROM uninteresting_table;


In JPA-land, I started by writing my own fetch query and added a dummy field to the database table to accomplish this. Class, let's say this together, "This sucks.". However, I did perform a little bit of JPA trickery to get what I want, with the custom fetch query and no dummy data field. In your persistent bean you'll simply annotate your column as follows:

  1. // Java code above....


  2. @Column(name="a+b", insertable=false, updatable=false)

  3. Long myNewColumn;


  4. //Java code below....



In the example above, you'll see I just injected my sql I want as that column name and the rest JPA handles for you. Other examples include:

  1. @Column(name="myFunc(a)", insertable=false, updatable=false)

  2. String functionResult;


  3. @Column(name="select count(*) from other_table where id = a", insertable=false, updateable = false)

  4. String queryResult;

1 comment:

Anonymous said...

This article was very useful for us! Thank you very much!
Olga