【问题标题】:Join JPA OneToOne relationship on Primary key columns在主键列上加入 JPA OneToOne 关系
【发布时间】:2015-03-10 20:17:48
【问题描述】:

我有两个表——表one和表two如下图——

表二:

    model    | customer_capacity| total

    samsung  | 300              | 20000

其中model 是表二的主键

表一:

    model     | count1 | addition | stuff

    samsung   | 20     | 34       | 2

其中 model 是 table one

的主键

以下是我创建的每个实体(表)的类 -

//表一:-

    @Entity
    @Table(name = "one")
    @NamedQueries({
            @NamedQuery(name = "getModelData",
                    query = "SELECT a.count1, a.addition, d.customerCapacity  FROM one a  JOIN FETCH two d where d.model = a.model and a.model = :model")
    })

public class One {
    @Id
    @Column(name = "model")
    private String model;

    @OneToOne
    @JoinColumn(name = "model", insertable = false, updatable = false)
    private Two t0;


    @Column(name = "count1")
    private double count1;

    @Column(name = "addition")
    private double addition;

    // getters and setters
}

//表二实体:

@Entity
@Table(name = "two")
public class Two {
    @Id
    @Column(name = "model")
    private String model;

    @Column(name = "customer_capacity")
    private int customerCapacity;

    @Column(name = "total")
    private String total;

    // getters and setters
}

问题陈述:-

我想在 JPA 中编写一个查询,它应该返回以下数据:

Select a.count1, a.addition, b.customer_capacity from one a, two b where a.model = b.model and a.model = 'samsung';

输出:

count1 | addition   | customer_capacity
20     |  34        | 300

但我不确定如何在 JPA 中进行这项工作?我正在尝试上面两个类中创建的命名查询,但每次它都给我错误 - 这是我用来提取数据的代码 -

 // method to get the data
public One getModelData(final String model) throws Exception {

    EntityManager em = factory.getPEntityManager();
    try {

        final Query q = em.createNamedQuery("getModelData");
        q.setParameter("model", mdoel);
        model = (One) q.getSingleResult();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        factory.closeEntityManager(em);
    }
    return model;
}

我得到的例外是 -

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.hello.jpa.One

我应该如何在 Java 中使用 JPQL 编写这样的连接查询?

【问题讨论】:

    标签: java hibernate postgresql jpa jpql


    【解决方案1】:

    如果您使用 NetBeans,您可以检查您的查询,只需右键单击 persistence.xml 文件,然后“运行 JPQL 查询”。在那里您可以快速测试您的查询并选择好的参数。

    【讨论】:

      【解决方案2】:

      从一个 a 中选择 a.count1、a.addition、a.t0.customerCapacity 其中 a.model = '三星';

      而且你不会简单地得到一个对象,它会返回一个对象数组 model = (One) q.getSingleResult();

      要获取 One 的对象,您需要编写,具有上述三个字段参数的 One 类中的正确构造函数,查询将变为

      select new One(a.count1, a.addition, a.t0.customerCapacity) from One a 其中 a.model = '三星';

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-22
        • 1970-01-01
        • 2023-03-12
        • 2021-03-15
        • 2016-05-26
        • 2011-02-28
        • 1970-01-01
        相关资源
        最近更新 更多