用的是hibernate4.28,在进行配置和映射时,只能用hibernate.properties和Configuration的addResource方法进行配置映射,而hibernate.cfg.xml一点作用也没有起到。
下面是代码和配置文件,第一段测试成功,第二段报错。
public class Test {
public static void main(String[] args) {
Student s = new Student();
s.setId(5);
s.setName("s5");
s.setAge(22);
Configuration cfg = new Configuration().addResource("com/wyf/hibernate/model/Student.hbm.xml");
ServiceRegistry sr = new ServiceRegistryBuilder().buildServiceRegistry();
SessionFactory sf = cfg.buildSessionFactory(sr);
Session session = sf.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
sf.close();
}
public class TestStudent {
public static void main(String[] args) {
Student s = new Student();
s.setId(6);
s.setName("s6");
s.setAge(22);
Configuration cfg = new Configuration();
cfg.configure();
ServiceRegistry sr=new ServiceRegistryBuilder().buildServiceRegistry();
SessionFactory sf =cfg.buildSessionFactory(sr);
Session session = sf.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
sf.close();
}
}
这是配置文件
<!-- Database connection settings -->
com.mysql.jdbc.Driver
jdbc:mysql//localhost
root
root
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</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 resource="com/wyf/hibernate/model/Student.hbm.xml"/>
<mapping class="com.wyf.hibernate.model.Teacher"/>