教程中的Hibernate示例不起作用

时间:2015-06-07 03:02:13

标签: hibernate configuration


我正在关注一个hibernate教程。我创建了 hibernate.cfg.xml
本教程的第一个例子不起作用。它抛出一个HibernateException,报告​​在调用 configure 方法时配置无效。我在这里留下了代码:

public static void main(String[] args) {
    Session session = null;
    try {
        Configuration configuration = new Configuration();
        configuration.configure();
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()
        ).buildServiceRegistry();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        session = sessionFactory.openSession();
        session.beginTransaction();
        System.out.println("Adding a customer record !");
        Customer customer = new Customer();
        customer.setCustomerName("Customer-a");
        customer.setCustomerAddress("Address1");
        session.save(customer);
        session.getTransaction().commit();
        System.out.println("Done!");
    } catch (HibernateException e) {
        System.out.println("=========>" + e.getMessage());
    } finally {
        if (session != null) {
            session.flush();
            session.close();
        }
    }
}

我的hibernate.cfg.xml就像:

<hibernate-configuration
xmlns="http://www.hibernate.org/xsd/hibernate-configuration"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-configuration hibernate-configuration-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<session-factory>
    <!-- Database connection settings -->
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.username">pepe</property>
    <property name="hibernate.connection.password">pepe</property>
    <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernate</property>
    <property name="connection_pool_size">1</property>
    <property name="hbm2ddl.auto">updated</property>
    <property name="show_sql">true</property>
    <mapping resource="hibernateexample1/domain/costumer.hbm.xml"/>
</session-factory>

1 个答案:

答案 0 :(得分:1)

你可能需要在hibernate-configuration之上添加hibernate DOCTYPE,这是

<?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" >

同时检查你的xml是否格式正确,查找任何未关闭的标签等,因为在配置文件中没有看到'hibernate-configuration'标签的关闭。