---
title: "hibernate hql return object or list 指定类型"
author: "aniyo"
date: "2017-01-25T17:58:07Z"
tags: []
categories: ["编程语言"]
slug: "hibernate-hql-return-object-or-list"
draft: false
lastmod: "2017-01-25T17:58:07Z"
id: 2354821
url: "https://aniyo.iteye.com/blog/2354821"
---

```
java.lang.ClassCastException: [Ljava.lang.Object; incompatible with com.shkco.adsr3.cbm.vo.ICustomerAccount
```

 

看到这错误都知道是数据类型转换不匹配，Object 与ICustomerAccount.

 

DAO 方法原始如下：

```
	public List<ICustomerAccount> getListOfCustomerAccount(ISessionContext sessionContext, IClientCentricCustomer clientCentricCustomer) {
		
		ISessionWrapper session = getCurrentSession();
		
		String sqlStr = "from " + CustomerAccount.class.getName() 
				+ " as cust join cust.companyGroup as cg where cg.compGrpId = "
				+ ":companyGroupId "
				+ " and cust.ccdRef= :ccdRef ";		
		
		Query query = session.createQuery(sqlStr);

		query.setParameter("companyGroupId", getCompGrpId(sessionContext));
		query.setParameter("ccdRef", clientCentricCustomer);
		
		
		return query.list();
	}
```

 

没有注意看代码，因为是直接写的from .....没有写select 对象，所以返回的就是Object.

修改如下即可:

加上Select cust,即ICustomerAccount 对象就ok啦。

```
	public List<ICustomerAccount> getListOfCustomerAccount(ISessionContext sessionContext, IClientCentricCustomer clientCentricCustomer) {
		
		ISessionWrapper session = getCurrentSession();
		
		String sqlStr = "select cust  from " + CustomerAccount.class.getName() 
				+ " as cust join cust.companyGroup as cg where cg.compGrpId = "
				+ ":companyGroupId "
				+ " and cust.ccdRef= :ccdRef ";		
		
		Query query = session.createQuery(sqlStr);

		query.setParameter("companyGroupId", getCompGrpId(sessionContext));
		query.setParameter("ccdRef", clientCentricCustomer);
		
		
		return query.list();
	}
```