【问题标题】:Hibernate example from a tutorial don't work教程中的休眠示例不起作用
【发布时间】:2015-08-21 18:27:49
【问题描述】:


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

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>

【问题讨论】:

  • 请输入您引用此示例的教程链接!!!!

标签: hibernate configuration


【解决方案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”标签的关闭。

【讨论】:

  • 谢谢!在这篇文章之后几分钟,我用 Netbeans 生成的代码替换了代码,然后它就可以工作了。问候
  • @LeandroRouraSixto 很高兴它的工作..!!干杯..如果有帮助,您可以接受答案..
猜你喜欢
  • 1970-01-01
  • 2015-11-16
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-15
  • 2016-12-29
  • 2015-10-28
相关资源
最近更新 更多