Java HibernateException:未设置“hibernate.dialect”时,对 DialectResolutionInfo 的访问不能为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21282432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
提问by Sameer Azeem
Creating a Hibernate Test Project using maven.
使用 maven 创建 Hibernate 测试项目。
when i run the project, it generates Exception:
当我运行项目时,它生成异常:
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)
But in main class required properties are set.don't know why programme is genrAating exception.
但是在主类中设置了必需的属性。不知道为什么程序会生成异常。
Main Class:
主要类:
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();
}
}
}
In POM file:
在 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>
Any idea where the problem can be??
知道问题出在哪里吗??
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;
}
回答by Keerthivasan
Set the configuration properties before applying configuration properties to the settings of StandardServiceRegistryBuilder
在将配置属性应用于设置之前设置配置属性 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);
Also, there seems to be a space at the end of the property keys while setting them. Please remove them.
此外,在设置属性键时,它们的末尾似乎有一个空格。请删除它们。
Based on the link, try changing this
根据链接,尝试更改此
configuration.setProperty("hibernate.dialect", "com.applerao.hibernatesqlite.dialect.SQLiteDialect");
to
到
configuration.setProperty("dialect", "com.applerao.hibernatesqlite.dialect.SQLiteDialect");
回答by Jimmy
You didn't initialize configuration, serviceRegistry, and sessionFactory correctly. From Hibernate 4.3.2.Final, StandardServiceRegistryBuilder is introduced. Please follow this order to initialize, e.g.
您没有正确初始化配置、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);
So in your code, you missed the step: configuration.configure()
.
因此,在您的代码中,您错过了以下步骤:configuration.configure()
.
回答by Eric Wang
In hibernate 4.3, it seems that need to use hibernate.properties to do config, use hibernate.cfg.xml only to include the .hbm.xml files, so, following is the solution:
在 hibernate 4.3 中,似乎需要使用 hibernate.properties 来做配置,使用 hibernate.cfg.xml 只包含 .hbm.xml 文件,因此,以下是解决方案:
in classpath, add a file: hibernate.properties and do all config here, e.g:
在类路径中,添加一个文件:hibernate.properties 并在此处进行所有配置,例如:
# 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
then, in hibernate.cfg.xml, only include the .hbm.xml files, e.g:
然后,在 hibernate.cfg.xml 中,只包含 .hbm.xml 文件,例如:
<?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>
tip: the official document didn't give any tip like this, I think it's a very bad thing.
提示:官方文档没有给出这样的提示,我认为这是一件非常糟糕的事情。
回答by Dinesh Khetarpal
Thanks for the solution. Somehow the 4.3.5 does not take the connection (Dialect) information from the hibernate.cfg.xml, use hibernate.properties file for that.
感谢您的解决方案。不知何故,4.3.5 没有从 hibernate.cfg.xml 获取连接(方言)信息,为此使用 hibernate.properties 文件。
回答by Omkar Patkar
This seems to be old question, but now when I am using 4.3.1 final Hibernate version I also came across this problem. After reading through many answers it seemed like they have really not taken care of it in the documentation but I went through the documentation and i think they have necessary information. It is not necessary that hibernate configuration needs to be in a .properties file, but it can be in xml file also.
这似乎是个老问题,但是现在当我使用 4.3.1 最终 Hibernate 版本时,我也遇到了这个问题。在阅读了许多答案后,他们似乎真的没有在文档中处理它,但我浏览了文档,我认为他们有必要的信息。hibernate 配置不需要在 .properties 文件中,但它也可以在 xml 文件中。
Just make sure you invoke configure()
before invoking build()
on the instance of StandardServiceRegistryBuilder
. This is because configure() actually loads the configuration from the default cfg.xml file and build actually uses it.
只需确保configure()
在调用build()
的实例之前调用StandardServiceRegistryBuilder
。这是因为 configure() 实际上是从默认的 cfg.xml 文件中加载配置并且 build 实际使用它。
To understand this, you can do one thing....before invoking configure()
.... invoke getSettings()
on the intance of StandardServiceRegistryBuilder
and print it...it's a Map.
要理解这一点,你可以做一件事....在调用之前configure()
....getSettings()
在实例上调用StandardServiceRegistryBuilder
并打印它...它是一个地图。
You will not see any hibernate properties you have mentioned in the cfg.xml
您将看不到 cfg.xml 中提到的任何休眠属性
Now invoke configure()
and print getSettings()
map....you will see...you have got all your properties.
现在调用configure()
并打印getSettings()
地图....您将看到...您已获得所有属性。
回答by alijandro
Here is what I did to make all the configurations in the code without hibernate.cfg.xml
or hibernate.properties
. Tested with hibernate version 4.3.8.Final. Hope it would be helpful.
这是我在没有hibernate.cfg.xml
或 的情况下对代码中的所有配置所做的工作hibernate.properties
。使用休眠版本 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);
回答by Abdourahmane FALL
As he say about ServiceRegistry :
正如他所说的 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;
}
}
回答by zaki
The configuration object was reading all the properties from the hibernate.cfg.xml
file. But the StandardServiceRegistryBuilder
object was not using those properties.
配置对象正在从hibernate.cfg.xml
文件中读取所有属性。但是该StandardServiceRegistryBuilder
对象没有使用这些属性。
This solution worked for me. The below statement is critical in making this work:
这个解决方案对我有用。以下声明对于完成这项工作至关重要:
ServiceRegistry serviceRegistry =
new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
Full solution:
完整解决方案:
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;
}
}
回答by sweetfa
This can also happen if the dialect cannot connect for any other reason, such as password expired.
如果方言由于任何其他原因无法连接,例如密码过期,也会发生这种情况。
Check for any earlier exceptions that may reveal the cause.
检查任何可能揭示原因的早期异常。
回答by Atul
In my case I was trying to connect to DB which is Mysql8+ version from my Java application. I face the same issue. The error logs are same but the reason for failure is different.
在我的情况下,我试图从我的 Java 应用程序连接到数据库,它是 Mysql8+ 版本。我面临同样的问题。错误日志相同,但失败的原因不同。
I made the change in my.cnf file of Mysql and it is: max-connect-errors=1000
我在 Mysql 的 my.cnf 文件中进行了更改,它是: max-connect-errors=1000
Default value is 100 but it wont work. So increases it to 1000, it starts working.
默认值为 100,但它不起作用。所以将它增加到 1000,它开始工作。
Need to look the logs in details in case of failure. If the logs contains this anywhere then try this thing.
如果出现故障,需要详细查看日志。如果日志在任何地方都包含此内容,请尝试此操作。
java.sql.SQLException: null, message from server: "Host 'X' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts'"
java.sql.SQLException:null,来自服务器的消息:“由于许多连接错误,主机 'X' 被阻塞;使用 'mysqladmin flush-hosts' 解除阻塞”