Transient Field in JPA and setting from Query

6.5k views Asked by At

How we can load transient fields in JPA from select queries.

For example I have this query:

SELECT table1.*, (SELECT SUM(field) from table2 WHERE theField=table1.flag) as total FROM table1;

So here I need a transient field called "total" in my bean.

But it seems it is not possible in JPA

1

There are 1 answers

4
Niks On

You can make use of a constructor in JPQL

Query:

SELECT NEW com.foo.entities.Table1(table1.*, (SELECT SUM(field) from table2 WHERE theField=table1.flag) as total) FROM table1;

Entity:

@Entity
public class Table1{

// .. other columns

@Transient
int total;

// table1Field1,table1Field2 etc. map to your table1.* coulmns
public Table1(String table1Field1,int table1Field2,int total){

// ..other assignments here

this.total = total; // transient assignment here

}


}