简体   繁体   中英

How do I Fetch Only Parent Records which has @OneToMany Relation with 2 other tables in JPA

I have 3 Entities 1.) Checklist 2.) Task 3.) Process

@OneToMany(mappedBy="checklist", cascade=CascadeType.PERSIST , fetch = FetchType.LAZY)
private List<taskEntity> tasks;

@OneToOne(mappedBy="checklist", cascade=CascadeType.PERSIST, fetch = FetchType.LAZY)
private processEntity process;

During Retrievel I used

@NamedNativeQuery(name="checklistEntity.selectAll", query="SELECT * FROM CHECKLIST", resultClass=checklistEntity.class)

But the output contains child tables records also.

With JPQL:

select c from checklistEntity c where class = checklistEntity

PS The general convention in Java is that class names should start with upper-case letters.

Probably it doesn't.

Did you see hibernate (I suppose...) log, and see that those two tables are fetch?

For those @OneToMany relationsheep you stated that you want a LAZY fetch. This mean that yes if you have object like this

Checklist() {
    List<Task> tasks .....
    Process process....
    ....
}

You can alway do checklist.getTasks()... and will get all values, but this doesn't mean that this values are fetch with checklistEntity.selectAll .

As far as I can see your code fetch only Checklists and live empty places where should be tasks and process, and fetch them when you ask for them,... when you call getter for one or the other property in Checklist.

Example :

  checklistEntity.selectAll
  Checklist c = // one of those Checklist fetch with this function.
  // c.tasks is empty
  // c.process is empty
  List<Task> list = c.getTasks();
  // list is not empty, in this line fetch for tasks is made
  Process p = c.getProcess();
  // p is not empty, in this line fetch for process is made.

I know it is hard to se that only Checklist is fetch because if you want to observe those values they are not null any more :D but this LAZY FETCH mean.

I suppose this is due performance? If so if you will never look at tasks and process inside this function this is ok (or if you will look only of few of them), but if you will look all or almost all of tasks and process than it is better that is loaded before. (use EGER).

Hope it help

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