JPA / Hibernate选择查询返回重复记录

我有一个表,比如,具有ID,State和User_ID的Instrument作为列。

所以我有这个JPA查询返回所有具有匹配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 instruments= query.getResultList(); for(Instrument instrument:instruments){ System.out.println("Instrument ID "+instrument.getID()); // using sysout as it is not prod code yet } 

它只返回与匹配记录重复多次的第一条记录。

 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 

我在Db中有三个记录,仪器ID为1,2和3

我在hibernate上启用了show sql查询,查询在数据库上直接运行并返回不同的记录。

Hibernate查询:

  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属性。

我从User_ID删除了它并将其添加到ID ,它工作正常。

我也遇到过同样的问题。 对于联系人表,我只将firstname列标记为@Id 。 并且表具有多个具有相同firstname行,因为具有相同firstname第一行记录在整个结果集中被复制。 为解决此问题,我将IdClass名字和姓氏作为id属性,并将其作为id类导入我的bean中。 由于firstnamelastname一起形成独特的组合,因此它解决了我的问题。

Idclass如下

 public class ContactKey implements Serializable{ protected String firstName; protected String lastName; public boolean equals(final Object inObject) { if (null != inObject) { if (inObject.getClass().equals(this.getClass())) { CqCamAdminKey siteKey = (CqCamAdminKey) inObject; return (null != this.getFirstName() && this.getFirstName().equals(siteKey.getFirstName()) && null != this.getLastName() && this.getLastName().equals(siteKey.getLastName())); } } return super.equals(inObject); } public int hashCode() { if (this.getFirstName() != null && this.getLastName() != null) { return this.getFirstName().hashCode() + this.getLastName().hashCode(); } return super.hashCode(); } } 

bean类如下

 @IdClass(contactKey.class) public abstract class CqCamAdminDataBean implements DataModelConstants{ private static final long serialVersionUID = 7686374823515894764L; @Id @JsonIgnore @XmlTransient @Column(name = FIRST_NAME) protected String firstName; @Id @JsonIgnore @Column(name = LAST_NAME) protected String lastName; }