在主键列上加入JPA OneToOne关系

时间:2015-01-12 23:33:12

标签: java hibernate postgresql jpa jpql

我有两个表 - 表one和表two,如下所示 -

表二:

    model    | customer_capacity| total

    samsung  | 300              | 20000

其中 模型是表格二的主键

表一:

    model     | count1 | addition | stuff

    samsung   | 20     | 34       | 2

其中 模型是表一的主键

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

//表一: -

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

从One a中选择a.count1,a.addition,a.t0.customerCapacity 其中a.model =' samsung';

你不会简单地得到Object of One,它会返回Object的数组 model =(One)q.getSingleResult();

要获得One的对象,你需要在One类中编写,正确的构造函数,如上面三个字段中的params,查询将变为

从One a中选择新的One(a.count1,a.addition,a.t0.customerCapacity) 其中a.model =' samsung';