HibernateException:当'hibernate.dialect'未设置时,对DialectResolutionInfo的访问不能为null

时间:2014-01-22 12:03:53

标签: java hibernate maven

使用maven创建一个Hibernate测试项目。

当我运行项目时,它会生成异常:

org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator initiateService
WARN: HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections
org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:209)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at org.hibernate.hibernatetest.App.main(App.java:33)
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.hibernatetest.App.main(App.java:51) 

但是在主类中需要设置属性。不知道为什么程序是genrAating异常。

主类:

public class App {

public static void main(String[] args) {
    Configuration configuration;
    ServiceRegistry serviceRegistry;
    SessionFactory sessionFactory;
    Session session = null;
    try {
        configuration = new Configuration();


        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        configuration.setProperty("hibernate.dialect ", "com.applerao.hibernatesqlite.dialect.SQLiteDialect");
        configuration.setProperty("hibernate.connection.url ", "jdbc:sqlite:TailorDB.db");
        configuration.setProperty("hibernate.connection.driver_class ", "org.sqlite.JDBC");
        configuration.setProperty("hibernate.connection.username ", "");
        configuration.setProperty("hibernate.connection.password ", "");
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        session = sessionFactory.openSession();

        CustomerModel c = new CustomerModel();
        c.setID(5);
        c.setNIC_Number("691201631345");
        c.setFirstName("Zee");
        c.setNumber("55225522");
        c.setLastName("Jan");
        c.setCustomerCode("Zee-123");

        session.beginTransaction();
        session.save(c);
        session.getTransaction().commit();
    } catch (HibernateException e) {
        e.printStackTrace();
    } finally {
        session.close();
    }
}
}

在POM文件中:

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.7.2</version>
    </dependency>
    <dependency>
        <groupId>com.applerao</groupId>
        <artifactId>hibernatesqlite</artifactId>
        <version>1.0</version>
    </dependency>
</dependencies>

知道问题出在哪里??

CustomerModel cLass:

@Entity
@Table(name = "Customer")

public class CustomerModel {

@Id
@GeneratedValue
@Column(name = "c_id")
int ID;
@Column(name = "c_code")
String customerCode;
@Column(name = "c_fname")
String firstName;
@Column(name = "c_mname")
String middleName;
@Column(name = "c_lname")
String lastName;
@Column(name = "c_nic")
String NIC_Number;
@Column(name = "c_email")
String email;
@Column(name = "c_pnumber")
String number;
}

11 个答案:

答案 0 :(得分:24)

您没有正确初始化configuration,serviceRegistry和sessionFactory。 从Hibernate 4.3.2.Final,引入了StandardServiceRegistryBuilder。请按照此顺序进行初始化,例如

    Configuration configuration = new Configuration();
    configuration.configure("com/jeecourse/config/hibernate.cfg.xml");

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
            configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

因此,在您的代码中,您错过了步骤:configuration.configure()

答案 1 :(得分:7)

这似乎是一个老问题,但现在当我使用4.3.1最终的Hibernate版本时,我也遇到了这个问题。在阅读了许多答案后,似乎他们在文档中没有真正处理它,但我查看了文档,我认为他们有必要的信息。 hibernate配置不一定需要在.properties文件中,但它也可以在xml文件中。

请确保在configure()的实例上调用build()之前调用StandardServiceRegistryBuilder。这是因为configure()实际上从默认的cfg.xml文件加载配置,而构建实际上使用它。

要理解这一点,你可以做一件事....在调用configure()之前....在getSettings()的内容上调用StandardServiceRegistryBuilder并打印它...它是一个地图。

您将看不到cfg.xml中提到的任何hibernate属性

现在调用configure()并打印getSettings()地图....你会看到......你已经拥有了所有属性。

答案 2 :(得分:4)

在hibernate 4.3中,似乎需要使用hibernate.properties来进行配置, 使用hibernate.cfg.xml只包含.hbm.xml文件, 所以,以下是解决方案:

在classpath中,添加一个文件:hibernate.properties 并在这里做所有配置, e.g:

# jdbc connecition
hibernate.connection.driver_class = org.postgresql.Driver
hibernate.connection.url = jdbc:postgresql://localhost:5432/xdm
hibernate.connection.username = postgres
hibernate.connection.password = 123456

# dialect
hibernate.dialect = org.hibernate.dialect.PostgreSQL82Dialect

# c3p0
hibernate.c3p0.min_size = 2
hibernate.c3p0.max_size = 5
hibernate.c3p0.max_statements = 20
hibernate.jdbc.batch_size = 10
hibernate.c3p0.timeout = 300
hibernate.c3p0.idle_test_period = 3000
hibernate.c3p0.testConnectionOnCheckout = true

# other
hibernate.show_sql = true
hibernate.max_fetch_depth = 3

然后,在hibernate.cfg.xml中,只包含.hbm.xml文件, e.g:

<?xml version='1.0' encoding='utf-8'?>
<!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>
        <!-- mapping files -->
        <mapping resource="hibernate/model/Event.hbm.xml" />
    </session-factory>
</hibernate-configuration>
提示:官方文件没有提供这样的提示,我认为这是一件非常糟糕的事情。

答案 3 :(得分:1)

在将配置属性应用于StandardServiceRegistryBuilder

的设置之前设置配置属性
    configuration.setProperty("hibernate.dialect", "com.applerao.hibernatesqlite.dialect.SQLiteDialect");
    configuration.setProperty("hibernate.connection.url", "jdbc:sqlite:TailorDB.db");
    configuration.setProperty("hibernate.connection.driver_class", "org.sqlite.JDBC");
    configuration.setProperty("hibernate.connection.username", "");
    configuration.setProperty("hibernate.connection.password", "");
    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

此外,在设置属性键时,似乎有一个空格。请删除它们。

根据link,尝试更改此

configuration.setProperty("hibernate.dialect", "com.applerao.hibernatesqlite.dialect.SQLiteDialect");

configuration.setProperty("dialect", "com.applerao.hibernatesqlite.dialect.SQLiteDialect");

答案 4 :(得分:0)

感谢您的解决方案。不知怎的,4.3.5没有从hibernate.cfg.xml获取连接(Dialect)信息,为此使用hibernate.properties文件。

答案 5 :(得分:0)

以下是我在没有hibernate.cfg.xmlhibernate.properties的情况下在代码中进行所有配置所做的工作。用hibernate版本4.3.8.Final测试。希望它会有所帮助。

    Configuration configuration = new Configuration();

    Properties properties = new Properties();

    properties.put(Environment.DRIVER,
            com.mysql.jdbc.Driver.class.getName());
    properties.put(Environment.USER, "root");
    properties.put(Environment.PASS, "root");
    properties.put(Environment.HBM2DDL_AUTO, "create");
    properties.put(Environment.DIALECT, MySQL5Dialect.class.getName());
    properties
            .put(Environment.URL, "jdbc:mysql://localhost/hibernate_test");
    properties.put(Environment.SHOW_SQL, true);

    configuration.setProperties(properties);

    configuration.addAnnotatedClass(Stock.class).addAnnotatedClass(
            StockDailyRecord.class);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();

    SessionFactory sessionFactory = configuration
            .buildSessionFactory(serviceRegistry);

答案 6 :(得分:0)

正如他所说的ServiceRegistry:

package org.phenix.hibernate.main;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {

            Configuration configuration = new Configuration();
            configuration.configure("hibernate.cfg.xml");

            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();

            // Create the SessionFactory from hibernate.cfg.xml
            return configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

答案 7 :(得分:0)

配置对象正在读取hibernate.cfg.xml文件中的所有属性。但是StandardServiceRegistryBuilder对象没有使用这些属性。

这个解决方案对我有用。以下陈述对于完成这项工作至关重要:

ServiceRegistry serviceRegistry = 
    new StandardServiceRegistryBuilder().applySettings(
        configuration.getProperties()).build();

完整解决方案:

package demo.jaxrs.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            Configuration configuration = new Configuration();
            configuration.configure();
            System.out.println("Properties: " + configuration.getProperties());
            StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();

            // Create the SessionFactory from hibernate.cfg.xml
            return configuration.buildSessionFactory(serviceRegistry);

         }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

答案 8 :(得分:0)

如果方言由于任何其他原因(例如密码已过期)无法​​连接,也会发生这种情况。

检查可能揭示原因的任何早期例外。

答案 9 :(得分:0)

就我而言,我试图从Java应用程序连接到Mysql8 +版本的数据库。我面临着同样的问题。错误日志相同,但失败原因不同。

我在Mysql的my.cnf文件中进行了更改,它是:max-connect-errors=1000

默认值为100,但无法使用。因此将其增加到1000,即可开始工作。

需要在失败时查看日志的详细信息。如果日志在任何地方都包含此内容,请尝试使用此东西。

  

java.sql.SQLException:空,来自服务器的消息:“主机'X'为   由于许多连接错误而被阻止;用'mysqladmin解除阻止   冲洗主机”“

答案 10 :(得分:0)

实体类中的

@id注释

在我的情况下,忘了在所有正确的配置之后添加@id注释,一旦我添加了注释,其工作正常

@Entity 
public class demo{

@Id
private long id

}