Column name as a parameter to Spring Data JPA Query

前端 未结 1 1020
花落未央
花落未央 2020-12-11 06:29

Is there a way to inject an Entity property dynamically to @Query? My need is to implement a method like follows:

@Query(\"select e from #{#enti         


        
相关标签:
1条回答
  • 2020-12-11 07:07

    You can do it using Spring Specification.

    Your specification method will be similar to the following one:

    public static Specification<Entity> byColumnNameAndValue(String columnName, String value) {
        return new Specification<Entity>() {
            @Override
            public Predicate toPredicate(Root<Entity> root,
                    CriteriaQuery<?> query, CriteriaBuilder builder) {
                return builder.equal(root.<String>get(columnName), value);
            }
        };
    }
    

    Please read a little about Specification, it's a great tool.

    https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

    and

    http://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/domain/Specifications.html

    0 讨论(0)
提交回复
热议问题