2017-08-28 52 views
0

如何在JPA查詢中添加額外的列?
假設我們有一個表「用戶」通過下面的僞代碼創建:JPA通過調用函數添加額外字段

create table users(name,birthdate); 

用戶JPA實體是這樣的:

@Entity 
@Table("users") 
public class User { 

    @Basic 
    @Column 
    private String name; 

    @Basic 
    @Column 
    private Date birthDate; 

    @Transient 
    private int age; 

    //getters and setters are here 
} 

注意,年齡場未在表exsists
我想在JQL中使用下面的查詢語句編寫

entityManager.createQuery(jql) 

並計算數據庫的年齡

select u.*, sysdate-u.birthdate age from users 
+0

我通常只會寫一個'public int getAge()'方法。我不知道爲什麼你需要在這裏介入數據庫。 –

+0

這只是一個例子。我以簡化的方式提到我的問題 –

回答

0

問題已解決。
查詢文本是這樣的:

String jql = "select NEW entity.User(u.id, u.name, u.birthDate, sysdate-u.birthDate as age) from User u"; 


,並且也是適當的構造函數被添加到實體

public User(int id, String name, Date birthDate, double age) { 
    this.id = id; 
    this.name = name; 
    this.birthDate = birthDate; 
    this.age = age; 
} 

並使用entitymanaget.createQuery(JQL)代替createNativeQuery

0

Usully我用這種方式解決這個問題:

select new name.of.package.users(u.*, sysdate - u.birthdate as age) from users u; 

編輯

這導致ORA-00923:FROM關鍵字未找到預期我的查詢 正文:String jql = "select new entity.User(u.*, sysdate-u.birthdate as age) from User u";

查詢包含一個錯誤:

select new entity.User(u.*, sysdate-u.birthdate as age) from User u 
//--------------------------------^^^ 
+0

它導致 ORA-00923:FROM關鍵字找不到預期的地方 我的查詢文本是: String jql =「select new entity.User(u。*,sysdate-u。出生日期作爲年齡)來自用戶u「; –

+0

您是否創建了一個JPQL或本地查詢@OracleMan –

+0

我已經測試了它們兩個 –

0

可能使用DB-查看可能的幫助。你想讓實體更新嗎?從「維護」實體派生出一個「只讀」實體是否合理?實例將包含計算列,方法是使用數據庫視圖作爲@Table?

create view usersview as name, birthdate, sysdate - birthdate as age from users; 

實體:

@Entity 
@Table("usersview") 
public class UserExtended extends User { 

如果你不想要兩個不同的實體 - 類(甚至當一個人從其他來源的),將有JPA允許如何在視圖上更新必要的一些探索,如果dbms支持它(oracle有),我沒有經驗,對不起。

+0

是的,它是一個好主意。 Oracle支持可編輯的視圖,默認情況下視圖在Oracle中是可編輯的。但我正在尋找更好的解決方案 –