ForEach方法中的类强制转换异常

时间:2018-05-15 08:08:04

标签: java spring hibernate orm

它是一个使用Spring 5&amp ;;的ORM应用程序。 Hibernate 5
我在DAO层使用Hibernate Callback接口来获取特定id之间的员工记录。我使用了命名参数:min & :最大的。虽然它成功地生成了查询,但在服务层中却抛出异常 我无法得到该异常的根本原因

DAOIMPL
------------

private static final String get_Records_By_Range="SELECT id,name,company,address,salary FROM EmployeeHLO where id>=:min and id<=:max";

@SuppressWarnings("unchecked")
    @Override
    public List<EmployeeHLO> getRecordsByIdRange(int start, int end) throws Exception {
        List<EmployeeHLO> listHlo= null;


        listHlo=  ht.execute(new HibernateCallback<List<EmployeeHLO>>() {
            @Override
            public List<EmployeeHLO> doInHibernate(Session ses) throws HibernateException {
                Query query= null;

                query= ses.createQuery(get_Records_By_Range);
                query.setInteger("min", start);
                query.setInteger("max", end);

                List<EmployeeHLO> listHloo= query.list();
                return listHloo;
            }

        });
        return listHlo


ServiceIMPL
-------------------

@Override
    public List<EmployeeDto> getRecordsByRange(int start, int end) throws Exception {
        List<EmployeeHLO> listHlo= null;
        List<EmployeeDto> listDto= new ArrayList<EmployeeDto>();

        //get records from dao
        listHlo= dao.getRecordsByIdRange(start, end);

        //copy hlo to dto

        listHlo.forEach(hlo->{   //getting error in this line
            EmployeeDto dto= new EmployeeDto();
            BeanUtils.copyProperties(hlo, dto);
            listDto.add(dto);
        });
        return listDto;
    }

测试
----------

try {

            //get record by range
            listDto= service.getRecordsByRange(1, 5);
            listDto.forEach(rangeDto->{
                System.out.println(rangeDto.getId()+" "+rangeDto.getName()+" "+rangeDto.getCompany()+" "+rangeDto.getAddress()+" "+rangeDto.getSalary());
            });


域名(EMployeeHLO)&amp;&amp; EmployeeDTo也包含相同的属性
----------------------

import java.io.Serializable;

public class EmployeeHLO implements Serializable {
    private int id;
    private String name;
    private String company;
    private String address;
    private float salary;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCompany() {
        return company;
    }
    public void setCompany(String company) {
        this.company = company;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public float getSalary() {
        return salary;
    }
    public void setSalary(float salary) {
        this.salary = salary;
    }

}


错误
-----------

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.st.domain.EmployeeHLO
    at java.util.ArrayList.forEach(Unknown Source)
    at com.st.service.EmployeeServiceImpl.getRecordsByRange(EmployeeServiceImpl.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:338)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy31.getRecordsByRange(Unknown Source)
    at com.st.test.Test.main(Test.java:46)


EmployeeHLO.hbm.xml
------------------------

<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.st.domain.EmployeeHLO" table="orm_table">
        <id name="id" column="id" length="10" type="int">
            <generator class="increment"></generator>
        </id>

        <property name="name" column="name" type="string" not-null="true" length="50"></property>
        <property name="company" column="company" type="string" not-null="true" length="50"></property>
        <property name="address" column="address" type="string" not-null="true" length="50"></property>
        <property name="salary" column="salary" type="float" precision="2" not-null="true" length="10"></property>
    </class>

    <query name="HQL_GET_RECORDS_BY_RANGE">
   <![CDATA[
     from EmployeeHLO where id>=:min and id<=:max
   ]]>
   </query>
</hibernate-mapping>

1 个答案:

答案 0 :(得分:2)

你必须选择实体,而不是它的所有字段或休眠将返回这些字段的列表,例如Object []的列表,因为有多种类型。

尝试将其更改为:

"SELECT emp FROM EmployeeHLO emp where emp.id>=:min and emp.id<=:max"

emp是表格EmployeeHLO的别名,我们可以在查询中使用它来简化。

当您引用实体的字段时,最好指向实体where emp.id而不是where id,因为您可以从多个表中虚拟选择或加入它们。

在select子句中,如果要返回实体而不是其他构造(例如,它总是List<Object[]>)来表示所选字段,则必须按别名选择整个表。

这样,hibernate可以完成他的魔法,并为每行返回一个实体实例,并且该字段已经填充了行值