【发布时间】:2018-11-04 22:21:14
【问题描述】:
我有 2 个数据库表 Customer 和 Items 有 1 -> many 关系。要从数据库中获取数据,我使用以下查询。
select customer.id, customer.name, items.itemName, items.itemPrice from testdb.customer INNER JOIN items ON items.customer_Id = customer.id
我有一个实体类客户
@Entity
public class Customer{
@Id
private int id;
@Column
private String name;
@Column
private String itemName;
@Column
private int itemPrice;
public Customer() {}
//Getter and setter are here
.......
}
在服务类中我有以下代码。
@GET @Path("/getCustomerInfo")
@Produces(MediaType.APPLICATION_JSON)
public List getCustomerInfo() {
CustomerDao dao = new CustomerDao();
return dao.getBuildingsCustomerInfo();
}
在我的 DAO 类中,我有以下代码
public List<Customer> getCustomerInfo(){
Session session = SessionUtil.getSession();
String queryString = "the above mentioned query";
List<Customer> customerInfo = session.createNativeQuery(queryString, Customer.class) ;
session.close();
return customerInfo;
}
我从服务收到以下 JSON 响应
[id:1, name:"Alfred", itemName:"jeans", itemprice:10],[id:1, name:"Alfred", itemName:"jeans", itemprice:10],[id:2, name:"James", itemName:"watch", itemPrice:20 ],[id:2, name:"James", itemName:"watch", itemPrice:20 ], [id:2, name:"James", itemName:"watch", itemPrice:20 ]
结果数为 5,这是正确的,但第二个结果是第 1 个的副本,第 4 个和第 5 个是第 3 个的副本。在第 2、第 4 和第 5 个结果中,itemName 和 itemPrice 应该不同。
如果我使用 createSQLQuery(queryString); 而不是 createNativeQuery(queryString, Customer.class); 我得到正确的结果,但没有实体属性名称。
[1, "Alfred", "jeans", 10],[1, "Alfred", "shirt", 15],[2, "James", "watch", 20], [2, "James", "coffee", 25], [2, "James", "drinks", 30]
我看过很多文章,但找不到解决方案。我必须使用 createNativeQuery() 而不是 createSQLQuery() 因为我需要映射实体类属性。如果我做错了什么,请告诉我。
【问题讨论】:
-
尝试选择不同的
-
@K.Nicholas 问题不在选择查询中。如果我在 MySQL 中或使用 createSQLQuery(queryString) 函数运行相同的查询,我会得到正确的结果。当我使用 createNativeQuery(queryString, Customer.class) 函数运行查询时,问题就出现了。
标签: sql json hibernate web-services hibernate-mapping