简体   繁体   中英

Spring Data Specifications, how to query LIKE for a @OneToMany relationship?

I have an entity, called "Client", which contains a List users.

public class Client {
    @OneToMany(fetch = FetchType.EAGER, mappedBy="client")
    private List<User> users;
}

I want to write a query which does something like:

SELECT *
FROM Client client
JOIN Users user
ON user.client_id = client.client_id
WHERE ( user.name LIKE '%name%' AND user.role = 'ADMINISTRATOR' )

Does anyone know how to do with using Specifications?

Normally, if there was one user, I would do something like this below. But since we have here a List I am not sure how to approach this situation.

Path<User> user = root.<User> get("user");
queryPredicates.add(cb.like(cb.upper(user .<String>get("name")), getLikePattern(queryString)));
queryPredicates.add(cb.like(cb.upper(user .<String>get("role")), "ADMINISTRATOR));

If I wanted to compare an equal, I could construct a User object and do something like this:

User user = new User();
// set properties
queryPredicates.add(cb.isMember(user, root.<Collection<User>>get("users")));

I could do something like:

Path<List<User>> users = root.<List<User>>get("users");

But then what?

Thanks, Joachim

解决方案可以在用户端,即在UserRepository中:

findByClientAndRoleAndNameLike(Client client, String role, String name)

You can use JPA entity manager query to do something like that :

List<Client> clients = (List<Client>) entityManager
    .createQuery(
        "select c from Client c join c.users u where u.role='ADMISTRATOR' and u.name like :name")
    .setParameter("name", "foo").getResultList();

You can find more about this here

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