想要循环调用Hibernate中的查询操作共12次,但是在第5次的时候就卡住了,不动了,像死循环了
求解
主函数:
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
WarningrecordapplyDAOImp wraDAO=new WarningrecordapplyDAOImp();
Date date1,date2;
for(int i=1;i<13;i++){
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
if(i<10){
date1=format1.parse("2009-0"+i+"-01");
date2=format1.parse("2009-0"+i+"-31");
}
else{
date1=format1.parse("2009-"+i+"-01");
date2=format1.parse("2009-"+i+"-31");
}
int number=wraDAO.warnapplyNumber(date1,date2);
}
}warnapplyNumber函数:
public int warnapplyNumber(Date time1, Date time2) throws Exception {
// TODO Auto-generated method stub
Session session = null;
Transaction trans = null;
int number=0;
try{
session=HibernateSessionFactory.getSession(); Query query = session.createQuery("from Warningrecordapply where eventTime between :time1 and :time2");
query.setDate("time1", time1);
query.setDate("time2", time2);
Iterator iterate = query.iterate();
while(iterate.hasNext())
{
number++;
}
}catch(HibernateException e){
if(trans!=null){
trans.rollback();//事务回滚
}
}finally{
session.close();
}
return number;
}
求解
主函数:
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
WarningrecordapplyDAOImp wraDAO=new WarningrecordapplyDAOImp();
Date date1,date2;
for(int i=1;i<13;i++){
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
if(i<10){
date1=format1.parse("2009-0"+i+"-01");
date2=format1.parse("2009-0"+i+"-31");
}
else{
date1=format1.parse("2009-"+i+"-01");
date2=format1.parse("2009-"+i+"-31");
}
int number=wraDAO.warnapplyNumber(date1,date2);
}
}warnapplyNumber函数:
public int warnapplyNumber(Date time1, Date time2) throws Exception {
// TODO Auto-generated method stub
Session session = null;
Transaction trans = null;
int number=0;
try{
session=HibernateSessionFactory.getSession(); Query query = session.createQuery("from Warningrecordapply where eventTime between :time1 and :time2");
query.setDate("time1", time1);
query.setDate("time2", time2);
Iterator iterate = query.iterate();
while(iterate.hasNext())
{
number++;
}
}catch(HibernateException e){
if(trans!=null){
trans.rollback();//事务回滚
}
}finally{
session.close();
}
return number;
}
不要放在循环里面,其他的没有发现什么错误。
不过query.iterate(); 会放在内存中,有缓存。
而list方法就不会,每次都会去数据库中取新的数据。
----ip围观党党员三十三号猜测是没有commit导致的