我正在使用Spring Data JPA的findAll()
来执行选择查询。但是,此结果将返回一些重复的记录,而不会返回其他记录。
我有两个POJO Student
和Class
。
Student
POJO:
@SuppressWarnings("serial")
@Entity
@Table(name="model_2", schema="vahanpgi")
public class Student implements Serializable {
@Column(name="m2_id")
private String stuId;
@Id
@Column(name="m2_des")
private String classId;
public String getStuId() {
return stuId;
}
@ManyToOne
@JoinColumn(name="m2_des", insertable = false, updatable = false)
private Class class1;
public void setStuId(String stuId) {
this.stuId = stuId;
}
public String getClassId() {
return classId;
}
public void setClassId(String classId) {
this.classId = classId;
}
public Class getClass1() {
return class1;
}
public void setClass1(Class class1) {
this.class1 = class1;
}
}
和Class
POJO:
@SuppressWarnings("serial")
@Entity
@Table(name="model_1", schema="vahanpgi")
public class Class implements Serializable {
@Id
@Column(name="m1_id")
private String classId;
@Column(name="m1_des")
private String className;
@OneToMany(mappedBy="class1")
private List<Student> student;
public String getClassId() {
return classId;
}
public void setClassId(String classId) {
this.classId = classId;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public List<Student> getStudent() {
return student;
}
public void setStudent(List<Student> student) {
this.student = student;
}
}
我在数据库中有两个表,分别为model_1
和model_2
:
model_1
表
MODEL_1
m1_id m1_des
cl_1 nur
cl_2 lkg
model_2
表
MODEL_2
m2_id m2_des
stu_1 cl_1
stu_2 cl_1
stu_3 cl_2
stu_4 cl_2
我正在触发findAll
查询,我的问题是我有四个学生,其中两个 ID分别为stu_1
和stu_3
的学生。
我的代码是:
Collection<Student> students= JpaStudent.findAll();
Iterator<Student> stuItr=students.iterator();
while(stuItr.hasNext())
{
int count=1;
System.out.println("Student id of student"+ count+ "is: " +stuItr.next().getStuId());
}
这是我得到的输出:
Student id of student1is: stu_1
Student id of student1is: stu_1
Student id of student1is: stu_3
Student id of student1is: stu_3
答案 0 :(得分:0)
问题在于您将@Id
批注放在Student
的错误字段上:
@Id // This is where you put it
@Column(name="m2_des")
private String classId;
由于classId
(m2_des
)不是唯一的,因此在您的情况下,Hibernate仅返回遇到的具有给定ID的第一个实体:
stu_1
(因为它是cl_1
的第一个)stu_3
(因为它是cl_2
的第一个)要解决此问题,必须将@Id
字段放在stuId
字段上:
public class Student implements Serializable {
@Id // This field is unique
@Column(name="m2_id")
private String stuId;
@Column(name="m2_des")
private String classId;
// ...
}