hibernate 里写sql的问题
在dao 里public List findByTitles(String title){
String hql="from News as news where news.title like'%"+title+"%'";
List list=
getHibernateTemplate().find(hql);
return list;
}用这个方法是没问题的,我想用sql语句实现.
用public List findByTitles(String title){
String sql="select * from news where title like'%"+title+"%'";
Session session=getSession();
Transaction tx=session.beginTransaction();
Query qu=session.createSQLQuery(sql);
tx.commit();
List list=qu.list();
return list;
}方法时报错
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]对象名 'news' 无效。
News.hbm.xml:
<hibernate-mapping>
<class name="org.imm.model.News" catalog="news" table="news" schema="dbo">
<id name="newsid" type="java.lang.Integer">
<column name="newid" ></column>
<generator class="native"></generator>
</id>
<property name="title" type="java.lang.String">
<column name="title" length="50"></column>
</property>
<property name="content" type="java.lang.String">
<column name="content" length="50"></column>
</property>
</class>
</hibernate-mapping>
请问怎么解决?
------解决方案-------------------- public List getUserList(){
//调用模板的execute方法,参数是实现了HibernateCallback接口的匿名类,
return (List) this.execute(new HibernateCallback(){
//重写其doInHibernate方法返回一个object对象,
public Object doInHibernate(Session session)
throws
HibernateException,
SQLException {
//创建query对象
Query query=session.createSQLQuery("select * from table");
//返回其执行了分布方法的list
return query.list();
}
});
}
------解决方案--------------------可以参考一下
/*根据库房Id和储位编码查询货物信息*/
public List findGoodsByWarehouseSlotCode(String warehouseId,String slotCode){
log.debug("finding WmsStockSlot instance with property:warehouseId " + warehouseId
+ ", stockCode: " + slotCode);
try {
String queryString = "SELECT * FROM WMS_STOCK_SLOT ss,WMS_BASE_GOODS g,WMS_BASE_GOODS_STATUS s WHERE ss.STOCK_GOODS_ID=g.GOODS_ID AND ss.STOCK_GOODS_STATUS=S.GOODS_STATUS_ID AND ss.STOCK_WAREHOUSE_ID=? AND ss.STOCK_SLOT_CODE=?";
Query queryObject = getSession().createSQLQuery(queryString).addEntity("stockSlot",WmsStockSlot.class).addEntity("goods",WmsBaseGoods.class).addEntity("goodsStatus",WmsBaseGoodsStatus.class);
queryObject.setParameter(0, warehouseId);
queryObject.setParameter(1, slotCode);
return queryObject.list();
} catch (
RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
------解决方案--------------------数据库发生了异常,你的sql语句有问题
String sql="form News n where n.title like'%"+title+"%'";
还有 别忘了关闭事务和session
------解决方案--------------------一般做Hibernate查询时不需要开启Transaction
public List findByTitles(String title){
String sql="select * from news where title like'%"+title+"%'";