简体   繁体   English

Spring Data JPA 中的动态@Query WHERE Cluase

[英]Dynamic @Query WHERE Cluase in Spring Data JPA

I'm using Spring Data JPA Repositories and would like to build custom WHERE clauses based on parameters passed through my method我正在使用 Spring Data JPA Repositories,并希望根据通过我的方法传递的参数构建自定义 WHERE 子句

Is it possible to set my WHERE clauses dynamically like so?是否可以像这样动态设置我的 WHERE 子句?

@Query("SELECT U FROM USERS U WHERE U.:columnName = :searchString)
List<User> findUserInfo(
@Param("columnName") String columnName,
@Param("searchString") String searchString);

So I could call my method like this:所以我可以这样调用我的方法:

findUserInfo("company", "Amazon")  

and it would create the query:它将创建查询:

SELECT U FROM USERS U WHERE U.company = 'Amazon'

and:和:

findUserInfo("address", "123 Billy Graham Drive",)  

would create the query:将创建查询:

SELECT U FROM USERS U WHERE U.address = '123 Billy Graham Drive'

No, it is not possible.不,这是不可能的。 JPA will validate the queries, and it cannot validate a WHERE condition where it cannot know the column name (or attribute name). JPA 将验证查询,并且它无法验证它不知道列名称(或属性名称)的 WHERE 条件。 So, you cannot.所以,你不能。 If you want do to something like that you should use Criteria, or Specification which is part of Spring Data JPA.如果你想做这样的事情,你应该使用 Criteria 或规范,它是 Spring Data JPA 的一部分。 This will allow you to create such dynamic queries but programmatically and not as JPQL queries.这将允许您以编程方式创建此类动态查询,而不是作为 JPQL 查询。

yes you can do this by using custom repository that extends QueryDslRepositorySupport是的,您可以使用扩展 QueryDslRepositorySupport 的自定义存储库来执行此操作

Please consider the below example请考虑以下示例

@Service 

Optional<User> findByEmail(String email);


@NoRepositoryBean
public interface UserRepositoryCustom {
    Optional<User> findByEmail(String email);
}

@Repository
public class UserRepositoryImpl extends QuerydslRepositorySupport implements UserRepositoryCustom {
    public UserRepositoryImpl() {
        super(User.class);
    }

    @Override
    public Optional<User> findByEmail(String email) {
        JPAQuery<User> query = getQuerydsl()
                .createQuery()
                .from(QUser.user)
                .where(QUser.user.email.equalsIgnoreCase(email))
                .select(QUser.user);
        return query.fetch().stream().findFirst();
    }
}

thus you can easily pass parameters to your JPA query.因此您可以轻松地将参数传递给您的 JPA 查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM