通过Junit测试,我调用了一个调用currentSession()
来获取会话对象的方法。
public final ThreadLocal session = new ThreadLocal();
public synchronized Session currentSession() {
Session s = (Session) session.get();
// Open a new Session, if this thread has none yet
if (s == null || !s.isOpen()) {
s = sessionFactory.openSession();
// Store it in the ThreadLocal variable
session.set(s);
}
return s;
}
代码挂起s = sessionFactory.openSession() ;
。下面是我的hibernate.properties和sessionFactory代码的初始化。我错过了什么?
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hsqldb.write_delay_millis=0
shutdown=true
hibernate.connection.pool_size=2
hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
hibernate.connection.provider_class=org.hibernate.connection.C3P0ConnectionProvider
hibernate.c3p0.acquire_increment=1
hibernate.c3p0.idle_test_period=100
hibernate.c3p0.max_size=100
hibernate.c3p0.max_statements=0
hibernate.c3p0.min_size=10
hibernate.c3p0.timeout=1800
hibernate.c3p0.preferredTestQuery=select 1
hibernate.c3p0.testConnectionOnCheckout=true
hibernate.c3p0.testConnectionOnCheckout=true
初始化sessionFactory代码
synchronized (this) {
if (sessionFactory == null) {
try {
String connection = "jdbc:mysql://"
+ Globals.DBSERVER.trim()
+ "/mydb?autoReconnect=true&failOverReadOnly=false&maxReconnects=10";
log.debug("Connection URL " + connection);
Configuration configuration = new Configuration();
configuration
.setProperty("hibernate.connection.username",
Globals.DB_USER_NAME.trim())
.setProperty("hibernate.connection.password",
Globals.DB_PASSWORD.trim())
;
configuration.configure();
sessionFactory = configuration
.buildSessionFactory(new ServiceRegistryBuilder()
.applySettings(
configuration.getProperties())
.buildServiceRegistry());
} catch (Exception e) {
log.fatal("Unable to create SessionFactory for Hibernate");
log.fatal(e.getMessage());
log.fatal(e);
e.printStackTrace();
}
}
if (sessionFactory == null) {
log.fatal("Hibernate not configured.");
System.exit(0);
}
log.info("Hibernate Configured Successfully!!!");
}
答案 0 :(得分:0)
我正在调用后台异步线程来进行数据库写入。在后台线程完成对数据库的写入之前,Junit正在退出。
我放了一个timeUnit,在flushData之后等待,它将任务排队等待写入,并且它有效。
@Test
public void test() {
logWrapper.flushData();
System.out.println("GeneralLogReadWriteTest test()");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
System.out.println("InterruptedException e");
}
}