How can I add columns dynamically to a Spring Data JPA @Query

后端 未结 3 1049
-上瘾入骨i
-上瘾入骨i 2021-01-23 03:43

Consider the following method on a Spring Data JPA interface:

@Query(\"select distinct :columnName from Item i\")
List findByName(@Param(\"columnName         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-23 04:25

    First of all you must implement custom Spring Data repository by adding interface:

    public interface ItemCustomRepository {
    
        List findBy(String columnName, String columnValue);
    
    }
    

    then you must extend your current Spring Data repository interface with newly created i.e.:

    public interface ItemRepository extends JpaRepository, ItemCustomRepository, QueryDslPredicateExecutor {
    
    }
    

    and then you must implement your interface using Query DSL dynamic expression feature (the name ItemRepositoryImpl is crucial - it will let you use original Spring Data repository implementation):

    public class ItemRepositoryImpl implements ItemCustomRepository {
    
        @Autowired
        private ItemRepository itemRepository;
    
        public List findBy(final String columnName, final String columnValue) {
            Path item = Expressions.path(Item.class, "item");
            Path itemColumnName = Expressions.path(String.class, item, columnName);
            Expression itemValueExpression = Expressions.constant(columnValue);
            BooleanExpression fieldEqualsExpression = Expressions.predicate(Ops.EQ, itemColumnName, itemValueExpression);
    
            return itemRepository.findAll(fieldEqualsExpression);
        }
    
    }
    

提交回复
热议问题