问题描述
我正在尝试使用休眠查询来搜索和过滤我的实体,但找不到任何解决方案。我有三个有界实体。
团体实体
public class Group {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private int id;
@Column
private String name;
@EqualsAndHashCode.Exclude
@OnetoMany(cascade={CascadeType.PERSIST,CascadeType.DETACH,CascadeType.MERGE,CascadeType.REFRESH})
@JoinTable(
name="students_groups",joinColumns=@JoinColumn(name="group_id"),inverseJoinColumns=@JoinColumn(name="student_id")
)
@LazyCollection(LazyCollectionoption.FALSE)
private List<Student> students;
}
学生实体
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private int id;
@Column(name="personal_number")
private int personalNumber;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column
private LocalDate birthday;
@Column
private String email;
@Enumerated(EnumType.STRING)
@Column(columnDeFinition="enum('MALE','FEMALE')")
private Gender gender;
@Column
private String address;
@EqualsAndHashCode.Exclude
@OnetoMany( cascade={CascadeType.PERSIST,CascadeType.REFRESH})
@JoinTable(
name="students_courses",joinColumns=@JoinColumn(name="student_id"),inverseJoinColumns=@JoinColumn(name="course_id")
)
@LazyCollection(LazyCollectionoption.FALSE)
private List<Course> courses;
public Student(int id) {
this.id = id;
}
public String getGender() {
if(gender==null)
gender = Gender.valueOf("MALE");
return gender.toString();
}
public void setGender(String gender) {
if(gender==null)
gender = "MALE";
this.gender = Gender.valueOf(gender);
}
}
和课程实体
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private int id;
@Column
private String name;
@Column
private String description;
}
我需要通过 group.id 和 course.id 找到 group 我尝试像这样进行查询
Query<Group> query = session.createquery("from Group as g join g.students as s join s.courses as c where c.id like :courseId and g.id like :groupId",Group.class);
但它不起作用:(我将非常感谢您帮助我解决这个问题,并为我的英语不好:)
解决方法
尝试以这种方式更正您的查询:
Query<Group> query = session.createQuery("select g from Group g join g.students s join s.courses c where c.id = :courseId and g.id = :groupId",Group.class);
请注意:
-
您只能将 like predicate 与
string_expression
一起使用。 -
@LazyCollection 不推荐使用
TRUE
和FALSE
值,因为您应该使用FetchType
、{{1} 的 JPA@ElementCollection
属性}} 或@OneToMany
集合。