我得到这个错误:
Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: org.hibernate.Session.close()Ljava/sql/Connection;
调用这个函数时:
private static SessionFactory factory;
public static void insert(Object model) {
factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
try {
session.save(model);
tx.commit();
} catch (HibernateException exc) {
if (tx != null)
tx.rollback();
exc.printStackTrace();
} finally {
session.close(); // here is when the error occurs
}
}
我相信我已经从最新的Hibernate 5.0.1的/lib/required/
目录中导入了所有必需的jar文件。
hibernate.cfx.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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3307/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property >
<mapping resource="customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
和customer.hbm.xml
映射文件:
<class name="com.test.app.model.Customer" table="customer">
<meta attribute="class-description">
Test.
</meta>
<id column="id" name="id" type="int">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
<property name="phoneNumbers" column="phone_numbers" type="string"/>
<property name="emailAddresses" column="email_addresses" type="string"/>
<property name="address" column="address" type="string"/>
<property name="note" column="note" type="string"/>
</class>
有什么问题吗?
看起来您的类路径中有两个hibernate-core-5.0.1.Final.jar
。例如,如果您在IDE中运行一个项目并使用hibernate-core-5.0.1.Final.jar
将其他项目添加到您的类路径中。
注:请不要在每次插入和回滚时都配置会话工厂,而不仅仅是在HibernateException
上。您可以在这里看到如何正确地处理事务,并且可以在这里找到一个使用Hibernate 5和MySQL的简单控制台项目示例。