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.
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,
Create a query. I.e.
@Query(value = "SELECT * FROM JOB WHERE USER_ID = ?1", nativeQuery = true)
Job getByUserId(Integer userId);
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With