无法从类型 [java.lang.Object[]] 转换为类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42446506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:39:00  来源:igfitidea点击:

Failed to convert from type [java.lang.Object[]] to type

javamysqlspringhibernatejpa

提问by twistezo

I have spring web app (JPA/Hibernate + MySQL). I have two DAO classes.

我有 Spring Web 应用程序(JPA/Hibernate + MySQL)。我有两个 DAO 类。

CustomerDAO

客户DAO

@Entity
@Table(name = "customers")
public class Customer {

  @Id
  @Column(name = "customer_id")
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @Column(name = "name", length = 50)
  private String name;

  @Column(name = "surname", length = 50)
  private String surname;

  @OneToMany(mappedBy = "customer")
  private Set<Order> orders = new HashSet<>();
}

OrderDAO

订单DAO

@Entity
@Table(name = "orders")
public class Order {

  @Id
  @Column(name = "order_id")
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @Column(name = "date")
  private Date date;

  @Digits(integer = 5, fraction = 2)
  @Column(name = "amount")
  private BigDecimal amount;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "customer_id")
  private Customer customer;

  @OneToMany(mappedBy = "order")
  private Set<OrderDetail> ordersDetails = new HashSet<>();

And i have a class for retrieving data from DB:

我有一个用于从数据库检索数据的类:

@Repository
public interface OrderDAO extends JpaRepository<Order, Long> {

    @Query("select o.customer.surname, sum(o.amount) as s from Order as o group by o.customer")
    List<Customer> findCustomersBySumOfAmount();

}

It is giving me result like this:

它给了我这样的结果:

+---------+---------------+
| surname | sum of amount | 
+---------+---------------+
|Bielecki | 141.49        | 
|Bielen   | 130.34        |
......

Now i want 'unbox' data from DB with this method List<Customer> findCustomersBySumOfAmount()

现在我想用这种方法从数据库“拆箱”数据 List<Customer> findCustomersBySumOfAmount()

I have method for this in my spring controller class:

我在我的 spring 控制器类中有这个方法:

 List<Customer> findCustomersBySumOfAmount = orderService.findCustomersBySumOfAmount();
 model.addAttribute("findCustomersBySumOfAmount", findCustomersBySumOfAmount);

 for(Customer c : findCustomersBySumOfAmount) {
     String s = c.getSurname();
     System.out.println(c);
 }

And i have error:

我有错误:

Failed to convert from type [java.lang.Object[]] to type [com.twistezo.models.Customer] for value '{Bielecki, 141.49}'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [com.twistezo.models.Customer]

无法从类型 [java.lang.Object[]] 转换为类型 [com.twistezo.models.Customer] 的值“{Bieecki, 141.49}”;嵌套异常是 org.springframework.core.convert.ConverterNotFoundException:找不到能够从 [java.lang.String] 类型转换为 [com.twistezo.models.Customer] 类型的转换器

I suppose it's because I'm getting List<Object[]>. I know that I can iterate between this List<Object[]>of my data but maybe there is some simpler way to retrieve data directly to <Customer>? I'm new in this stuff. Since now I used methods like List<Customer> findAll()without @Query annotation and i'm looking for similar "unboxing".

我想这是因为我得到了List<Object[]>. 我知道我可以在List<Object[]>我的数据之间进行迭代,但也许有一些更简单的方法可以将数据直接检索到<Customer>?我是这方面的新手。从现在起我使用了List<Customer> findAll()没有 @Query 注释的方法,我正在寻找类似的“拆箱”。

I was trying do something like this (add Customer.class in query) without effect:

我试图做这样的事情(在查询中添加 Customer.class)没有效果:

@Query("select o.customer.surname, sum(o.amount) as s from Order as o group by o.customer", Customer.class) List<Customer> findCustomersBySumOfAmount();

@Query("select o.customer.surname, sum(o.amount) as s from Order as o group by o.customer", Customer.class) List<Customer> findCustomersBySumOfAmount();

采纳答案by Maciej Kowalski

I would suggest creating a POJO class just to store the results of that query:

我建议创建一个 POJO 类来存储该查询的结果:

package com.mypackage;

public class CustomerAmountResult{

    private String surname;
    private BigDecimal amountSum;

    public CustomerAmountResult(String surname, BigDecimal amountSum){
       this.surname = surname;
       this.amountSum = amountSum;
    }

    // getters / setters
}

Then change your query to the following:

然后将您的查询更改为以下内容:

@Query("select NEW com.mypackage.CustomerAmountResult(
            o.customer.surname, sum(o.amount)) 
        from Order as o
        group by o.customer.surname") 
List<CustomerAmountResult> findCustomersBySumOfAmount();

Thanks to that you will not need to parse the result set manually.

多亏了这一点,您将不需要手动解析结果集。

回答by demaroar

I already had this error message. In my case, I was doing something like the code below:

我已经收到此错误消息。就我而言,我正在做类似下面的代码:

@Repository
public interface RepositoryA extends CrudRepository<EntityA, Long> {

  @Query(nativeQuery = true, value = " ...SQL_1... ")
  List<EntityA> getListOfEntityA(...PARAMS_1...);

  @Query(nativeQuery = true, value = " ...SQL_2... ")
  List<EntityB> getListOfEntityB(...PARAMS_2...);

}

I was parameterizing the repository interface with an "EntityA" and had an other method returning other type parametrized with an "EntityB".

我正在使用“EntityA”参数化存储库接口,并使用其他方法返回使用“EntityB”参数化的其他类型。

In your case you are parameterizing the JpaRepository with "Order" and then using a method that returns a list of "Customer"s... Maybe this is causing this exception.

在您的情况下,您使用“订单”参数化 JpaRepository,然后使用返回“客户”列表的方法......也许这导致了此异常。

回答by raminr

Your query select o.customer.surname, sum(o.amount) as s from Order as o group by o.customerdoesn't return Customer. The Customer entity expects the result set to at least look like:

您的查询select o.customer.surname, sum(o.amount) as s from Order as o group by o.customer没有返回Customer。Customer 实体期望结果集至少如下所示:

|   id   | name   | surname |
-----------------------------
|   1    | john   | smith   |
|   2    | james  | white   |
|   3    | sara   | black   | 

That's how the Result Set gets mapped into Customer entity. If you want to stick to your query, then change the return type to List<Object[]>, and run through the list and extract the data that you want.

这就是结果集被映射到客户实体的方式。如果您想坚持查询,请将返回类型更改为 ,然后List<Object[]>遍历列表并提取所需的数据。