日期:2014-05-20  浏览次数:20744 次

求助!! Hibernate 中使用createSQLQuery()的使用问题!!!!
在使用HIBERNATE的时候,程序   (数据库是   sqlserver2000)

String   t_n= "tname ";
String   ssql= "select   id   from   sysobjects   where   name= ' "+t_n+ " ' ";
Query   query;
query=session.createSQLQuery(ssql);
Object   objs=(Object)l.iterator().next();
int   id=((Integer)objs).intValue();


为什么总报异常:[Ljava.lang.Object;   cannot   be   cast   to   java.lang.Integer
id   明明是int型啊     这个是怎么会事啊?
createSQLQuery()方法的结果怎么取呀?????


------解决方案--------------------
给你个简单查询的例子吧,希望有用

public static void main(String[] args) {
HibernateUtil.setup( "create table EVENTS ( uid int, name VARCHAR, start_Date
date, duration int, location_id int); ");
HibernateUtil.setup( "create table locations ( uid int, name VARCHAR, address
VARCHAR); ");
// hibernate code start
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
Location location = new Location();
location.setName( "USA ");
location.setAddress( "Address ");
session.save(location);

Event e= new Event();
e.setId(11111L);
e.setName( "testSave ");
e.setStartDate(new Date());
e.setLocation(location);
e.setName( "testSave ");

session.save(e);

List results =
session.createQuery( "from Event e where e.name= 'testSave ' ").list();

System.out.println(results.size());

tx.commit();
HibernateUtil.closeSession();

HibernateUtil.sessionFactory.close();

// hibernate code end

HibernateUtil.checkData( "select * from events; ");

}

------解决方案--------------------
你试试这样

createSQLQuery( "SELECT * FROM CATS ")
.addScalar( "id ", Hibernate.INTEGER)

把id指定成integer
------解决方案--------------------

------解决方案--------------------
有必要这么麻烦??
String t_n= "tname ";
String hql= "select id from sysobjects where name= ' "+t_n+ " ' ";
List list = session.createQuery(hql).list();
Iterator iterator = list.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next()+ " ");
}
不就OK了????