简体   繁体   中英

How to retrieve specific members of a collection using Hibernate?

I am wondering if there is any way to retrieve a record and specific number of its members of collection.

I have a class called MyGroup which keeps a list of Students, each student can be in one group at a time. I need to retrieve list of available students of each group. If I retrieve all the students of each group and find available ones it needs a big amount of memory to run a loop through the collection and check the available field of each student.

On the other hand, (Bidirectional) if I execute a select clause on students to retrieve those students that are available, in this way I am retrieving the group class record as well (since it is a member of student). So for each of students I am retrieving its fields + group's fields.

Sample data

Group 1
Name available
Jack  true
Luke  false
Nou   true
...

Group 2
Name available
Mike   false
George false
Alex   true
...

Expected Result

Name Available Group GroupName
Jack true       1     Wolfs
Nou  true       1     Wolfs
Alex true       2     Tigers

Classes

@Entity
public class Student {
    @Id
    @GeneratedValue
    private long id;
    private String name;
    private boolean available;
    @OneToOne
    private MyGroup group;

    getters and setters
}

@Entity
public class MyGroup {
    @Id
    @GeneratedValue
    private long id;
    private String name;
    @OneToMany
    private List<Student> student = new ArrayList();

    getters and setters
}

In the hibernate by default lazy loading is true so if you are executing a select clause on the students table and fetching students so by default with one student object u will get the group id as the foreign key and i think not all the records of the associated group object will fetch atonce .If u want to fetch the list of students associated with the group object later u can do that but due to the lazy loading list of students associated with a group object will not fetch atonce .I think this is your major problem.You do not want to fetch the list of students associated with a group atonce.I think your current student table structure will be like this .

id name group_id
 1 jack  1
 2  joe  2
 3  Mack 1

if you can add one more field boolean available then your query can be more specific like the student which belong to a group id and avialble true.

Boolean available

now your student table structure will be like this.

id name group_id available
1   jack 1         true
2    Joe  2         true
3    Mack  1        false

so now u can query specific set of student based on available boolean field

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM