我有一个使用 Hibernate 的网络项目。项目结构为:
src
|
|--java
| |--com.rusakov...
|
|--resources
| |--hibernate.cfg.xml
|
|--webapp
|--WEB-INF
我的 hibernate.cfg.xml 看起来像:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/computersdb</property>
<property name="connection.username">root</property>
<property name="connection.password">34902</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping package="com.rusakov.entities"/>
</session-factory>
</hibernate-configuration>
我的初始化类SessionFactory
:
public class HibernateUtil {
private static SessionFactory sessionFactory = null;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration
.buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry());
} catch (HibernateException e) {
e.printStackTrace();
}
}
return sessionFactory;
}
}
Entity
班级:
public class UserEnt {
private int id;
private String login;
private String password;
private String name;
private String surname;
public UserEnt() {};
//** setters and getters **//
}
当我试图将User
对象保存到数据库时,我得到了这个:
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
org.hibernate.HibernateException: /hibernate.cfg.xml not found
我打电话的班级SessionFactory
package com.rusakov.util;
import com.rusakov.entities.*;
import org.hibernate.Session;
public class test {
public static void main(String[] args) {
UserEnt user = new UserEnt();
user.setName("test");
user.setSurname("test");
user.setLogin("test");
user.setPassword("test");
user.setRole("test");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
我做错了什么?