sql - Hibernate createNativeQuery 返回重复的行
问题描述
我有 2 个数据库表Customer和Items有 1 -> many 关系。要从数据库中获取数据,我使用以下查询。
从 testdb.customer 中选择 customer.id、customer.name、items.itemName、items.itemPrice 在 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,这是正确的,但第 2 个结果是第 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() 因为我需要映射实体类属性。如果我做错了什么,请告诉我。
解决方案
不确定重复背后的确切原因,但SELECT DISTINCT
会解决您的问题,因为它只需要不同的记录。
推荐阅读
- php - 创建价值对象的最佳方式是什么?
- c# - 提供 FluentAssertions 的扩展
- c - C中的十六进制到整数转换
- pandas - 确定数据是数据框还是函数中的数据框列表
- tensorflow - TFX Evaluator 似乎无法识别 ResolverNode 的基线模型输出
- python - Python 模块“处理”、“多处理”和其他并发模块:有什么区别?
- python - 这是继承,如果不是,它是什么?
- javascript - 尝试构建我的游戏板 - 但遇到未定义的 ID 问题
- sql - 由于内部错误,不支持相关子查询模式 - 不存在相关子查询
- c++ - 如何在 MacOS/X 程序中重命名程序名称菜单标签?