尝试打印多个结果集。但是列表只返回对象

时间:2011-08-08 14:56:00

标签: java hibernate

我正在尝试的这个查询来自多个表。

    SQLQuery query = session.createSQLQuery("select t.id as ID,
                                                    t.companyname as COMPANYNAME,
                                                    e.fullname as FULLNAME,
                                                    e.empid as EMPID,
                                                    ca.dateallocated as DATEALLOCATED 
                                             from   bw_tempclientdetails t,
                                                    bw_employee_details e,
                                                    bw_clientallocation ca 
                                             where  e.empid=ca.empid and                                       
                                                    ca.companyname=t.companyname ");

但是query.list只返回我无法转换为字符串表示的对象。任何解决方案?

1 个答案:

答案 0 :(得分:0)

您可以创建POJO。像一个小班:

/**
* Dto.
*/
class MyClass {
    int id;
    String companyName;
    String fullName;
    int empId;
    Date dateAllocated;

    public MyClass() {
    }

    public MyClass(int id, String companyName, String fullName, int empId, Date dateAllocated) {
        this.id = id;
        this.companyName = companyName;
        this.fullName = fullName;
        this.empId = empId;
        this.dateAllocated = dateAllocated;
    }
    // Rest of code
}

这样做Hibernate允许您实例化每行返回一个对象。这是一个包含结果的完整列表。

如果某些元素可以为空,那么最好使用对象(Integer而不是int)。

实例化对象:

select new package.MyClass(colA, colB...)

在我们的例子中

SQLQuery query = session.createSQLQuery("select new a.b.MyPojo(t.id as ID,
                                                t.companyname as COMPANYNAME,
                                                e.fullname as FULLNAME,
                                                e.empid as EMPID,
                                                ca.dateallocated as DATEALLOCATED)
                                         from   bw_tempclientdetails t,
                                                bw_employee_details e,
                                                bw_clientallocation ca 
                                         where  e.empid=ca.empid and                                       
                                                ca.companyname=t.companyname ");

将返回List<MyPojo>,每行一个元素。这就是你想要的吗?