本文介绍了没有基础表的JPA实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类,该类可以映射到使用JPA本机查询从数据库中提取的结果。有没有办法将没有底层表的实体映射到结果?
我提到链接,它允许它冬眠。这可以使用JPA来完成吗?

I want to create a class that can be mapped to a result extracted from the database using JPA native query. Is there a way to map an entity without an underlying table to the result?I referred to this link which allows it for hibernate. Can this be done using JPA instead?

这是我希望结果映射的类。

This is my class for which I want the result to be mapped.

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规范定义了返回的方式从本机查询到非实体类的结果

JPA 2.1 specification defines the means to return the result from a native query to a non entity class

您应该签出标题 3.10.16.2返回非托管实例,特别是

You should checkout the heading 3.10.16.2 Returning Unmanaged Instances especially the

3.10.16.2.2构造器结果
$ b

3.10.16.2.2 Constructor Results


$ b

示例

example

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)})
        })

这篇关于没有基础表的JPA实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 07:14