我正在使用spring hibernate开发一个应用程序,我正在使用HibernateUtil类生成hibernate会话。
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
try {
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
现在我在春天写了一个计划类,它反复向服务器请求。
@Scheduled(fixedRate = 3000)
public void sendNotification() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
Date currentDate = new Date();
System.err.println("Current Date "+dateFormat.format(currentDate));
List<ImageInfo> listImageInfo = imageInfoDao.getImageOfParticularDate(currentDate);
if (listImageInfo.size() > 0) {
List<User> listUser = userDao.getAppUser("1");
for (ImageInfo imageInfo : listImageInfo) {
for (User user : listUser) {
pushNotification(user.getRegId(), pushGroupNumNotification(imageInfo.getGroupNum()),"POST");
}
}
}
}
这是我的Dao功能
public List getImageOfParticularDate(Date date) {
List<ImageInfo> imageInfoList = new ArrayList<>();
try {
session = getSession();
imageInfoList = session.createQuery("select img from ImageInfo img where img.active = 0 and img.publishedTime <:publishedTime ").setParameter("publishedTime", date).list();
session.createQuery("update ImageInfo img set img.active = 1 where img.active = 0 and img.publishedTime <:publishedTime ").setParameter("publishedTime", date).executeUpdate();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
session.close();
}
return imageInfoList;
}
你可以看到我正在使用getSession()函数获得hibernate会话。这是我的getSession()函数,我正在使用HibernateUtil进行会话。
public Session getSession() {
return HibernateUtil.getSessionFactory().openSession();
}
现在,由于调度程序在一段时间后经常向服务器请求我得到异常&#34;连接太多&#34;。你可以看到我在结束时关闭了我的会话。我怎么解决呢?