首页 > 解决方案 > Hibernate createNativeQuery 返回重复的行

问题描述

我有 2 个数据库表CustomerItems有 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() 因为我需要映射实体类属性。如果我做错了什么,请告诉我。

标签: sqljsonhibernateweb-serviceshibernate-mapping

解决方案


不确定重复背后的确切原因,但SELECT DISTINCT会解决您的问题,因为它只需要不同的记录。

请参阅using-distinct-in-jpa


推荐阅读