Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

java - Column name as a parameter to Spring Data JPA Query

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 #{#entityName} e where e.***columnName*** = ?2")
List<T> findAll(String ***columnName***, String value);

Any other simple ways of doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...