gpt4 book ai didi

java - 没有基础表的 JPA 实体

转载 作者:IT老高 更新时间:2023-10-28 13:54:01 24 4
gpt4 key购买 nike

我想创建一个可以映射到使用 JPA native 查询从数据库中提取的结果的类。有没有办法将没有基础表的实体映射到结果?我提到了this允许它 hibernate 的链接。这可以改用 JPA 来完成吗?

这是我想要映射结果的类。

import java.math.BigDecimal;
import javax.persistence.Entity;
@Entity
public class OpUsage {
String username;
BigDecimal number_of_clicks;
String accordion;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public BigDecimal getNumber_of_clicks() {
return number_of_clicks;
}
public void setNumber_of_clicks(BigDecimal number_of_clicks) {
this.number_of_clicks = number_of_clicks;
}

public String getAccordion() {
return accordion;
}

public void setAccordion(String accordion) {
this.accordion = accordion;
}
}

最佳答案

JPA 2.1 specification定义将本地查询的结果返回到非实体类的方法

您应该查看标题 3.10.16.2 Returning Unmanaged Instances 尤其是

3.10.16.2.2 构造函数结果

The mapping to constructors is specified using the ConstructorResult annotation element of the SqlResultSetMapping annotation. The targetClass element of the ConstructorResult annotation specifies the class whose constructor corresponds to the specified columns. All columns corresponding to arguments of the intended constructor must be specified using the columns element of the ConstructorResult annotation in the same order as that of the argument list of the constructor. Any entities returned as constructor results will be in either the new or the detached state, depending on whether a primary key is retrieved for the constructed object.

示例

Query q = em.createNativeQuery(
"SELECT c.id, c.name, COUNT(o) as orderCount, AVG(o.price) AS
avgOrder" +
"FROM Customer c, Orders o " +
"WHERE o.cid = c.id " +
"GROUP BY c.id, c.name",
"CustomerDetailsResult");

@SqlResultSetMapping(name = "CustomerDetailsResult",
classes = {
@ConstructorResult(targetClass = com.acme.CustomerDetails.class,
columns = {
@ColumnResult(name = "id"),
@ColumnResult(name = "name"),
@ColumnResult(name = "orderCount"),
@ColumnResult(name = "avgOrder", type = Double.class)})
})

关于java - 没有基础表的 JPA 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28945146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com