Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid Spring Data Jpa doing join on simple select?

Tags:

java

spring

jpa

I have entity with @ManyToOne linking, when I use criteria to execute query, spring use cross join, but I just want to select on own column.

the case:

public class Job {

   @Column
   private Long jobId;

   @OneToMany(fetch = FetchType.EAGER)
   @JoinColumn(name="creator", referencedColumnName="uid")
   private User creator;

}

public class User {


   @Column
   private Long uid;

   @Column
   private String name;

}

public Predicate toPredicate(Root<Job> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    List<Predicate> Predicates=new ArrayList<Predicate>();

   Predicates.add(cb.equal(root.get("creator").get("uid"), 123456));
   query.where(Predicates.toArray(new Predicate[Predicates.size()]));
   return null;
}

I just want to create query like "select ... from job where user_id = 123456", but spring execute like "select ... from job m cross join user u where m.creator = u.uid and u.uid = 123456".

How to avoid join use Criteria in ManyToOne link, just select on own column.

like image 927
elevenights Avatar asked Oct 31 '25 19:10

elevenights


2 Answers

I think you should set fetch type to lazy : (fetch = FetchType.LAZY), or remove it, it's LAZY by default for @OneToMany.

This way hibernate (not spring), will do a simple select query on your Job table. But if you keep it to EAGER, hibenate will always use join on User table to get it's data, on the other side, with LAZY mode, the query to get User data will be fired only when you do job.getCreator(), but in this case the transaction/session should be kept open.

Regards,

like image 99
adam66 Avatar answered Nov 03 '25 09:11

adam66


Create a query. I.e.

@Query(value = "SELECT * FROM JOB WHERE USER_ID = ?1", nativeQuery = true)
Job getByUserId(Integer userId);

Source

like image 37
Graciano Avatar answered Nov 03 '25 08:11

Graciano