简体   繁体   中英

JPA CriteriaQuery join only entities which match the Criteria

I have been working on a code to build a Criteria Query to do a conditional join. But its not quit correct. Please consider following example:

I have 2 Entities Owner and Car . Owner has OneToMany relation with Car .

在此处输入图片说明

On code Owner entity has List of Car s.(Using @OneToMany with FetchType.LAZY )

Owner.java:

@Entity
public class Owner {

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    private int id;
    private String name;
    private String email;

    @OneToMany(mappedBy="owner",fetch=FetchType.LAZY)
    private List<Car>  cars;

    ...
}

Car.java

@Entity
public class Car{

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private int id;
    private String manufacturer;
    private String regnumber;

    @ManyToOne
    @JoinColumn(name="ownerid")
    private Owner owner;
    ...
} 

Now my requirement is simple I want to get all the Owners of TESLA cars. Following code works good for that:

CriteriaQuery<Owner> cq = cb.createQuery(Owner.class);
Root<Owner> rootowner = cq.from(Owner.class);
rootowner.fetch("cars");

cq.distinct(true);

Join<Owner, Car> carjoin= rootowner.join(Owner_.cars);
Expression<String> carmanExp = carjoin.get(Car_.manufacturer);
Predicate p = cb.like(carmanExp, "TESLA");
cq.where(p);

TypedQuery<Owner> tq = em.createQuery(cq);

Now my requirement is, if a Owner owns 2 cars, one is TESLA and another is VOLVO. I want Owner entity should contain only TESLA .

How do I do that?

You cannot do what you are asking in a simple JPA query on the fly, as that is a manipulation of the JPA Entity in such a way that it no longer represents what is in the database. Put another way, when JPA gives you back the Owner referencing just the Tesla, what do you want it to do with the now removed Volvo when it synchronizes with the database?

In your case, the easiest solution would be to just query for the cars you want instead, as they have a reference to their owners. You will get duplicates where an owner may have two or more teslas - you can work out this problem by creating a map of owners to cars with the results yourself.

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