在主键列上加入 JPA OneToOne 关系

Join JPA OneToOne relationship on Primary key columns

我有两个 tables - Table one 和 Table two 如下所示 -

Table二:

    model    | customer_capacity| total

    samsung  | 300              | 20000

其中模型是table两个的主键

Table一个:

    model     | count1 | addition | stuff

    samsung   | 20     | 34       | 2

其中模型是table一个[=的主键 20=]

下面是我创建的每个实体 (tables) 的 类 -

//Table一个:-

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

//Table两个实体:

@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 中编写一个查询,它应该 return 我以下数据:

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 编写这样的连接查询?

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

select a.count1, a.addition, a.t0.customerCapacity 来自一个 a a.model = 'samsung';

而且你不会简单地得到一个对象,它会return个对象数组 型号 = (一) q.getSingleResult();

要得到 One 的对象,你需要写,Proper constructor in One class 具有上述三个字段的参数,查询将变为

select new One(a.count1, a.addition, a.t0.customerCapacity) from One a a.model = 'samsung';