使用休眠的程序不会终止
我使用Hibernate创建了一个程序。
程序到达主功能端,但程序正在运行。
我想知道它是否发生在使用Hibernate版本4.x配置时。SessionFactory
配置方式是否错误?
manual1_1_first_hibernate_apps.java
public static void main(String[] args) {
args[0] ="list";
if (args.length <= 0) {
System.err.println("argement was not given");
return;
}
manual1_1_first_hibernate_apps mgr = new manual1_1_first_hibernate_apps();
if (args[0].equals("store")) {
mgr.createAndStoreEvent("My Event", new Date());
}
else if (args[0].equals("list")) {
mgr.<Event>listEvents().stream()
.map(e -> "Event: " + e.getTitle() + " Time: " + e.getDate())
.forEach(System.out::println);
}
Util.getSessionFactory().close();
}
private <T> List<T> listEvents() {
Session session = Util.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<T> events = Util.autoCast(session.createQuery("from Event").list());
session.getTransaction().commit();
return events;
}
利用.java
private static final SessionFactory sessionFactory;
/**
* build a SessionFactory
*/
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
// hibernate version lower than 4.x are as follows
// # it successful termination. but buildSessionFactory method is deprecated.
// sessionFactory = new Configuration().configure().buildSessionFactory();
// version 4.3 and later
// # it does not terminate. I manually terminated.
Configuration configuration = new Configuration().configure();
StandardServiceRegistry serviceRegistry =
new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
/**
* @return built SessionFactory
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
以下控制台日志代码段在程序终止时使用 buildSessionFactory 方法。
2 08, 2014 8:42:25 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:derby:D:\Java\jdk1.7.0_03(x86)\db\bin\testdb]
但是如果不使用不推荐使用的buildSessionFactory方法并终止(程序正在运行),则不会出现上述两行。
环境:
Hibernate 4.3.1 DERBY JRE 1.8 IntelliJ IDEA 13