我试图让Hibernate使用现有的Connection对象连接到我的MariaDB数据库,我从Tomcat连接池中获取或通过DriverManager.getConnection(...)
创建。两种方式都有效,我收到一个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()
时,我得到一个有效的Session对象,我可以在Hibernate中执行select-Statements。但是,当我尝试调用session.persist(someobj)
时,我得到以下异常:
Exception in thread "main" java.lang.UnsupportedOperationException: The application must supply JDBC connections
我已经搜索了几个小时都有同样问题但没有成功的人,非常感谢任何帮助!
EDIT1:
我的hibernate配置如下所示:
<?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)
答案 0 :(得分:0)
尝试
return sb.openStatelessSession(connection);
或
sessionFactory.withOptions().connection(Connection conn);
return sb.openSession();