超过两个实体的休眠复杂查询
Posted
技术标签:
【中文标题】超过两个实体的休眠复杂查询【英文标题】:Hibernate complex query for more then two entity 【发布时间】:2021-03-04 18:48:08 【问题描述】:我正在尝试进行休眠查询以搜索和过滤我的实体,但我找不到任何解决方案。我有三个有界实体。
团体实体
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.DETACH, CascadeType.MERGE, 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 查找分组我尝试像这样进行查询
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);
但它不起作用:(我将非常感谢你帮助我解决这个问题,并为我的英语不好:)
【问题讨论】:
【参考方案1】:尝试以这种方式更正您的查询:
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
值,因为您应该使用 @ElementCollection
、@OneToMany
或 @ManyToMany
集合的 JPA FetchType
属性。
【讨论】:
以上是关于超过两个实体的休眠复杂查询的主要内容,如果未能解决你的问题,请参考以下文章