我试图让Hibernate使用我从Tomcat连接池获取或通过DriverManager.getConnection(...)
创建的现有连接对象连接到我的MariaDB数据库。两种方法都起作用,我收到一个Connection对象,可以同时执行读取和写入操作。现在,我想将这些对象提供给Hibernate。我已选择这样做:
public class SessionFactoryService implements ISessionFactoryService {
private SessionFactory sessionFactory = null;
private final Connection connection;
@Inject
public SessionFactoryService(Connection connection){
this.connection = connection;
}
public Session getSession(){
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
SessionBuilder sb = sessionFactory.withOptions();
return sb.connection(connection).openSession();
}}
[当我调用getSession()
时,我得到一个有效的会话对象,可以在Hibernate中对其执行选择语句。但是,当我尝试调用session.persist(someobj)
时,出现以下异常:
Exception in thread "main" java.lang.UnsupportedOperationException: The application must supply JDBC connections
我已经搜索了几个小时内遇到相同问题但没有成功的人,非常感谢您的帮助!
EDIT1:
我的休眠配置看起来像这样:
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name = "hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<mapping class="com.xxx.yyy.Object"></mapping>
</session-factory>
</hibernate-configuration>
由于连接对象已在外部设置,因此我仅在hibernate.cfg.xml
中设置方言。
完整的堆栈跟踪看起来像这样:
Exception in thread "main" java.lang.UnsupportedOperationException: The application must supply JDBC connections
at org.hibernate.engine.jdbc.connections.internal.UserSuppliedConnectionProviderImpl.getConnection(UserSuppliedConnectionProviderImpl.java:44)
at org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:48)
at org.hibernate.id.enhanced.TableStructure$1.getNextValue(TableStructure.java:125)
at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:452)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:782)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:767)
at com.xxx.yyy.ServiceA.create(ServiceA.java:75)
at com.xxx.yyy.App.main(App.java:60)
return sb.openStatelessSession(connection);
或
sessionFactory.withOptions().connection(Connection conn);
return sb.openSession();