【发布时间】: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