【问题标题】:@Query annotation is not reading native sql select * spring data@Query 注解没有读取原生 sql select * spring data
【发布时间】:2016-11-22 03:51:28
【问题描述】:
public interface ConsumerRepository extends CrudRepository<Consumer, Long>  {

    List<Consumer> findByLastName(String lastName);
    List<Consumer> findByFirstName(String firstName);

    //List<Consumer> readExistsFirstName(String firstName);
    //List<Consumer> getByFirstNameAndLastNameOrderByFirstName();
    //Collection<Consumer> findById(Long id);
    @Query("select c from Consumer as c where c.firstName like '%?1%'")
    Collection<Consumer> findByNameContains(String word);

    @Query(value = "SELECT ppc_consumer FROM ppc_consumer WHERE lastname = ?1",
            countQuery = "SELECT count(*) FROM ppc_consumer WHERE lastname = ?1",
            nativeQuery = true)
    Page<Consumer> findByLastname(String lastname, Pageable pageable);
 }

但是显示错误“预期不同”,得到 * 因为我在 @Query 注释中使用了 *?请问怎么了?

【问题讨论】:

  • 这里为什么要使用原生查询?您实际上可以直接获取 ppc_consumer 记录,对吗?能详细点吗?
  • @developer 你问我一个问题?我需要答案

标签: java spring spring-data-jpa


【解决方案1】:

你不能在 spring jpa 中使用 * 你必须使用别名。试试这个方法:

@Query(value = "SELECT ppc FROM ppc_consumer ppc WHERE ppc.lastname = ?1",
            countQuery = "SELECT count(ppc) FROM ppc_consumer ppc WHERE ppc.lastname = ?1")

查看这个问题了解更多信息

Does Spring Data JPA have any way to count entites using method name resolving?

【讨论】:

  • 这是因为nativeQuery=true 命令。我编辑了答案,我尝试删除它,它对我有用。
  • 你的例子也很完美,但你也可以添加 * 例子:)
【解决方案2】:

让我们像下面的例子那样做-

@Query(value = "SELECT * FROM consumer WHERE lastname = :lastName  LIMIT :maxRecord", nativeQuery = true)
StickerProduct findWalletProduct(@Param("lastName") String lastName, @Param("maxRecord") Long maxRecord);

另一种代替 * 的方法:

@Query(value = "SELECT c FROM consumer c WHERE lastname = :lastName  LIMIT :maxRecord", nativeQuery = true)
StickerProduct findWalletProduct(@Param("lastName") String lastName, @Param("maxRecord") Long maxRecord);

我希望它有效。谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    相关资源
    最近更新 更多