HQL查询如何返回实体?

时间:2019-01-18 05:52:40

标签: hibernate hql

您好,我正在努力使此查询成功执行。我有这两个实体,都具有适当的获取器和设置器。

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

    @Id
    @Column(name="Customer_Code")
    private String customer_Code;

    @Column(name="Customer_Name")
    private String customer_Name;
}


 @Entity
@Table(name="project")
public class Project {

    @Id
    @Column(name="Project_Code")
    public String project_Code;

    @Column(name="Project_Customer")
    public String project_Customer;

    @Column(name="Project_Description")
    public String project_Description;

    @Column(name="Project_Pastel_Prefix")
    public String project_Pastel_Prefix;

    @Column(name="Project_Name")
    public String project_Name;
}

十个是我的控制器方法:

// need to inject the session factory
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<Customer> getCustomers() {

        // get the current hibernate sessio
    Session currentSession = sessionFactory.getCurrentSession();

    // create a query  ... sort by last name
    Query<Customer> theQuery = 
            currentSession.createQuery("Query goes here",
                                        Customer.class);

    // execute query and get result list
    List<Customer> customers = theQuery.getResultList();

        // return the results       
        return customers;
    }

我正在尝试执行以下查询“ SELECT DISTINCT Customer。* FROM Customer,Project WHERE Customer_Code = Project_Customer ORDER BY Customer_Name

我尝试了以下方法:

  • ”从“客户”中选择不同的客户作为客户,从“项目”中选择专业客户 cus.customer_code =按cus.customer_Name命名的pro.project_Customer订单”
  • ”从客户中选择不同的cus.customer_Code,cus.customer_Name 作为cus,将项目作为pro,其中cus.customer_code = pro.project_Customer由cus.customer_Name订购”
  • ”来自Project pro客户cus,其中cus.customer_Code = 按cus.customer_Name的pro.project_Customer订单“

但是没有任何效果。我通常会收到错误无法使用请求的结果类型[com.timesheet_Webservice.entity.Customer] 创建具有多个返回值的查询的TypedQuery

这似乎意味着我没有像通过简单的“来自客户”查询那样获得客户实体的实例。如果是这样,我该如何退还客户实体?如果没有,那我在做什么错了?

1 个答案:

答案 0 :(得分:1)

当您执行Customer.*时,查询应选择两个customer_Code对象customer_NameString。但是您期望将Customer实体作为结果。

进行查询以选择一个Customer对象,

select distinct cus from Customer as cus, Project as pro where cus.customer_code = pro.project_Customer order by cus.customer_Name