2017-08-28 448 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中是可编辑的。但我正在寻找更好的解决方案 –