当前位置: 代码迷 >> Java Web开发 >> Hibernata无主键表查询有关问题
  详细解决方案

Hibernata无主键表查询有关问题

热度:5430   发布时间:2013-02-25 21:09:33.0
Hibernata无主键表查询问题
自动生成的HBM
  <class name="com.cntomorrow.zyqx.entity.Yhgwdz" table="用户岗位对照表" schema="TELEUSER">
  <composite-id name="id" class="com.cntomorrow.zyqx.entity.YhgwdzId">
  <key-many-to-one name="yhjbxx" class="com.cntomorrow.zyqx.entity.Yhjbxx" lazy="false">
  <column name="用户ID" length="6" />
  </key-many-to-one>
  <key-many-to-one name="gwxx" class="com.cntomorrow.zyqx.entity.Gwxx" lazy="false">
  <column name="岗位ID" length="6" />
  </key-many-to-one>
.......
 
还有两个类,一个只有ID属性的类,一个有其他属性的类(因为表没有主键)
然后我想加个条件,只能加到这个只有ID属性的类里面。
如下:
Yhgwdz yhh=new Yhgwdz();//只有id属性的那个类
  YhgwdzId yy=new YhgwdzId();//其他属性的类
  Page page=new Page();
  Yhjbxx yh=new Yhjbxx();
  yh.setYhid(212);//加入条件
  yy.setYhjbxx(yh);
  yhh.setId(yy);//加入条件
 
然后通过这个查询
Session sss = getSession();
  Criteria criteria = sss.createCriteria(Yhgwdz.class);
  
  if (yhgwdz != null) {
  if (yhgwdz.getId() != null && !"".equals(yhgwdz.getId())) {
  criteria.add(Restrictions.eq("id", yhgwdz.getId()));
  }
List lii = criteria.list();
 
 
结果我发现他把所有条件都给列上了。肯定是除了我传的那个条件,剩下的都为空,所以导致查不出东西来。不传条件一切正常。以下是自动生成sql语句:
select this_.用户ID as 用户ID6_0_, this_.岗位ID as 岗位ID6_0_, this_.部门ID as 部门ID6_0_, this_.加入时间 as 加入时间6_0_, this_.批准人ID as 批准人ID6_0_, this_.操作者ID as 操作者ID6_0_ from TELEUSER.用户岗位对照表 this_ where (this_.用户ID=? and this_.岗位ID=? and this_.部门ID=? and this_.加入时间=? and this_.批准人ID=? and this_.操作者ID=?)
 
 
 
求解怎么修改正常

------解决方案--------------------------------------------------------
Java code
Session session = HibernateSessionFactory.getSession(); Transaction tran = session.beginTransaction();Query query = session.createSQLQuery("select * from userInfowhere yhid=? and yhjbxx=?"); query.setString(0, ""); query.setString(你数据库字段的位置, "");tran.commit();List l = query.list(); if(l.size() != 0 ){ System.out.println(l.size());         }         else{             System.out.println("login fail");        }     }
------解决方案--------------------------------------------------------
你的dao实现类可以继承HibernateDaoSupport
public class QueryDaoImpl extends HibernateDaoSupport implements QueryDao

可以使用sessionfactory,SessionFactory sessionFac= this.getSessionFactory();
  相关解决方案