JPA / Hibernate选择查询返回重复记录 [英] JPA/Hibernate select query returning duplicate records
问题描述
我有一个表,比如,带有ID,State和User_ID的工具作为列。
I have a table ,say, Instrument with ID,State, and User_ID as columns.
所以我有这个JPA查询返回所有的仪器记录匹配
User_ID。
So I have this JPA query to return all the instrument records with a matching User_ID.
query = manager.createQuery("SELECT instrument from Instrument instrument
where instrument.User_ID=:User_ID",Instrument.class);
query.setParameter("User_ID", User_ID);
List<Instrument> instruments= query.getResultList();
for(Instrument instrument:instruments){
System.out.println("Instrument ID "+instrument.getID());
// using sysout as it is not prod code yet
}
它只返回第一条记录重复次数与匹配记录一样多次。
It is returning only the first record repeated as many times as there are matching records.
11:13:01,703 INFO [stdout] (http-/127.0.0.1:8080-1) Instrument ID 1
11:13:01,704 INFO [stdout] (http-/127.0.0.1:8080-1) Instrument ID 1
11:13:01,704 INFO [stdout] (http-/127.0.0.1:8080-1) Instrument ID 1
I在Db中有三个记录,仪器ID为1,2,3和
I have three records in Db with instrument IDs 1,2, and 3
我在hibernate上启用了show sql查询,并且查询在数据库上直接运行
和返回不同的记录。
I enabled show sql query on hibernate and the query runs fine on the Database directly and returns distinct records.
Hibernate查询:
Hibernate Query:
select instrumentjdo0_.User_ID as member_U1_0_, instrumentjdo0_.ID as ID2_0_,
instrumentjdo0_.state as state4_0_ from instrument instrumentjdo0_ where instrumentjdo0_.User_ID=?
工具实体
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "instrument")
public class Instrument{
@Id
@Column(name="User_ID", length=9, unique=true, nullable=false)
String user_ID;
@Column(name="ID",nullable=false)
String ID;
@Column(name="state",nullable=false)
String state;
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getUserID() {
return user_ID;
}
public void setUserID(String userID) {
this.user_ID = userID;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
不确定我缺少什么。
推荐答案
问题是Instrument Entity中的错误列有 @ID
属性分配给它。
The issue was that the wrong column in the Instrument Entity had the @ID
attribute assigned to it.
我从 User_ID
中删除了它并将其添加到 ID
并且工作正常。
I removed it from User_ID
and Added it to ID
and it worked fine.
这篇关于JPA / Hibernate选择查询返回重复记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!