我有一个Spring Boot项目。我将资源文件夹放在hibernate.cfg.xml文件中。 这是我的hibernate.cfg.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">***</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/exportbatch?serverTimezone=UTC</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
</session-factory>
我有一个hibernateUtil类,用于实例化一个休眠会话。
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try
{
// Create the SessionFactory from hibernate.cfg.xml
// return new Configuration().configure().buildSessionFactory();
return new AnnotationConfiguration().configure().buildSessionFactory();
}
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);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void shutdown()
{
// Close caches and connection pools
getSessionFactory().close();
}
}
在我的应用程序控制器中,我有一个要向其请求mysql数据库的端点。
@RequestMapping("/getbuildinginfo/{buildingid}")
public void getbuildinginfo(String buildingid)
Session session = null;
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String query = "select * from exportbatch.exportbatch";
SQLQuery sqlQuery = session.createSQLQuery(query);
List<Object[]> rows = sqlQuery.list();
HibernateUtil.shutdown();
这在我第一次运行项目时很好用,但是如果我第二次调用端点,则会收到此异常: org.hibernate.service.UnknownServiceException:请求了未知服务[org.hibernate.engine.jdbc.connections.spi.ConnectionProvider]
有人可以帮我吗?为什么它第一次起作用?是Spring Boot上下文问题吗?如果是,我该如何解决?