如果我只想查询出一条记录,比如说我是按id查询的,这样就只能查出来一条记录,那我应该用什么方法? Session session = null;
Entity e = null;
try{
session = HibernateSessionFactory.getSession();
String sql = "from Entity where Id:=id";
Query query = session.createQuery(sql);
query.setInteger("id", uid);
List list = query.list();
Iterator it = list.iterator();
if(it.hasNext()){
e = (Entity) it.next();
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
session.close();
}
return e;有可以只查单条的方法吗?
Entity e = null;
try{
session = HibernateSessionFactory.getSession();
String sql = "from Entity where Id:=id";
Query query = session.createQuery(sql);
query.setInteger("id", uid);
List list = query.list();
Iterator it = list.iterator();
if(it.hasNext()){
e = (Entity) it.next();
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
session.close();
}
return e;有可以只查单条的方法吗?
public Object getByPrimaryKey(Class type, Serializable pk)
{ Object o = new Object(); try
{
o = getHibernateTemplate().get(type, pk);
}
catch (Exception e)
{
e.printStackTrace();
} return o;
}
其中type是实体对象的类型,pk是主键,比如查一个User,那么可以直接调用该方法getByPrimaryKey(User.class, 2),就是查询主键为2的User用户,如果
只是使用hibernate,你可以查查对应的方法,时间长了不太记得了,呵呵
才能使用getHibernateTemplate()方法
Iterator it = list.iterator();
if(it.hasNext()){
e = (Entity) it.next();
}
为什么要这样写?多条:
List<Entity> list = (List<Entity>) query.list(); 单条
Entity entity = query.uniqueResult() ;
mysql
如下:
select * from duty limit 0, 1;
转化为HQL
可能是这样
select {dty.*} from duty dty limit 0, 1;一般都采用主键查询。这个方式不保证能对。