使用Spring CrudRepository进行自定义查询

时间:2019-05-27 13:58:45

标签: java spring spring-boot spring-data-jpa

我正在学习JPA框架,但无法执行自定义查询。

我已经完成了本教程: https://spring.io/guides/gs/accessing-data-jpa/ 现在我想做一个自定义查询,例如"SELECT firstName,lastName FROM Customer"

我尝试过:

public interface CustomerRepository extends CrudRepository<Customer, Long> {

    @Query("SELECT firstName,lastName FROM Customer")
    Iterable<Customer> findAll();

    List<Customer> findByLastName(String lastName);
}

但是我得到java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to hello.Customer

我的代码与本教程中的代码相同,除了在我调用的33行应用程序上

for (Customer customer : repository.findAll()) {
                log.info(customer.toString());
            }

测试我的自定义查询

我希望为我记录每个客户的数据,但是这使我异常: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to hello.Customer

1 个答案:

答案 0 :(得分:1)

您可以使用 @Query("SELECT new your.package.Customer(firstName,lastName) FROM Customer")

获取所需的对象。如果您只需要一个名字和姓氏的对象,我将使用另一个对象。