12.04.2014, 00:15. Показов 4004. Ответов 0
Доброго времени суток.
Имеются следующие файлы в проекте:
HibernateUtil.java
| Java |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| package org.hibernate.util;
import org.hibernate.SessionFactory;
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 {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure("/hibernate.cfg.xml").buildSessionFactory(
new StandardServiceRegistryBuilder().build() );
}
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;
}
} |
|
hibernate.hbm.cfg
| XML |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| <?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>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/blog_db</property>
<property name="connection.username">postgres</property>
<property name="connection.password">1</property>
<property name="connection.pool_size">1</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.internal.NoCachingRegionFactory</property>
<property name="show_sql">true</property>
<mapping class="org.blog.dto.UserDetails" />
</session-factory>
</hibernate-configuration> |
|
users.hbm.xml
| XML |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.mapping">
<class name="org.blog.dto.UserDetails" table="users">
<id name="userId" column="id" type="java.lang.Integer">
<generator class="increment" />
</id>
<property name="login" column="login" type="java.lang.String" />
<property name="password" column="password" type="java.lang.String" />
</class>
</hibernate-mapping> |
|
UserDetails.java
| Java |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
| package org.blog.dto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class UserDetails {
@Id
@Column(name="id")
private int userId;
@Column(name="login")
private String login;
@Column(name="password")
private String password;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
} |
|
Вот так запускаю:
Hibernate.java
| Java |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| package org.hibernate;
import org.blog.dto.UserDetails;
import org.hibernate.util.HibernateUtil;
public class Hibernate {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserId(1);
user.setLogin("test");
user.setPassword("1");
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.getTransaction().commit();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
HibernateUtil.getSessionFactory().close();
}
} |
|
И выдает вот такой стек ошибок:
Кликните здесь для просмотра всего текста
| Java |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
| /usr/lib/jvm/java-7-oracle/bin/java -Didea.launcher.port=7540 -Didea.launcher.bin.path=/opt/idea-IU-135.480/bin -Dfile.encoding=UTF-8 -classpath /usr/lib/jvm/java-7-oracle/jre/lib/jfxrt.jar:/usr/lib/jvm/java-7-oracle/jre/lib/resources.jar:/usr/lib/jvm/java-7-oracle/jre/lib/javaws.jar:/usr/lib/jvm/java-7-oracle/jre/lib/jsse.jar:/usr/lib/jvm/java-7-oracle/jre/lib/charsets.jar:/usr/lib/jvm/java-7-oracle/jre/lib/management-agent.jar:/usr/lib/jvm/java-7-oracle/jre/lib/plugin.jar:/usr/lib/jvm/java-7-oracle/jre/lib/rt.jar:/usr/lib/jvm/java-7-oracle/jre/lib/jfr.jar:/usr/lib/jvm/java-7-oracle/jre/lib/jce.jar:/usr/lib/jvm/java-7-oracle/jre/lib/deploy.jar:/usr/lib/jvm/java-7-oracle/jre/lib/ext/zipfs.jar:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunpkcs11.jar:/usr/lib/jvm/java-7-oracle/jre/lib/ext/dnsns.jar:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunec.jar:/usr/lib/jvm/java-7-oracle/jre/lib/ext/sunjce_provider.jar:/usr/lib/jvm/java-7-oracle/jre/lib/ext/localedata.jar:/opt/projects/BlogProject/out/production/BlogProject:/opt/projects/libs/hibernate-release-4.3.5.Final/lib/required/antlr-2.7.7.jar:/opt/projects/libs/hibernate-release-4.3.5.Final/lib/required/dom4j-1.6.1.jar:/opt/projects/libs/hibernate-release-4.3.5.Final/lib/required/hibernate-commons-annotations-4.0.4.Final.jar:/opt/projects/libs/hibernate-release-4.3.5.Final/lib/required/hibernate-core-4.3.5.Final.jar:/opt/projects/libs/hibernate-release-4.3.5.Final/lib/required/hibernate-jpa-2.1-api-1.0.0.Final.jar:/opt/projects/libs/hibernate-release-4.3.5.Final/lib/required/jandex-1.1.0.Final.jar:/opt/projects/libs/hibernate-release-4.3.5.Final/lib/required/javassist-3.18.1-GA.jar:/opt/projects/libs/hibernate-release-4.3.5.Final/lib/required/jboss-logging-3.1.3.GA.jar:/opt/projects/libs/hibernate-release-4.3.5.Final/lib/required/jboss-logging-annotations-1.2.0.Beta1.jar:/opt/projects/libs/hibernate-release-4.3.5.Final/lib/required/jboss-transaction-api_1.2_spec-1.0.0.Final.jar:/opt/projects/libs/postgresql-9.3-1101.jdbc41.jar:/opt/idea-IU-135.480/lib/idea_rt.jar com.intellij.rt.execution.application.AppMain org.hibernate.Hibernate
Apr 10, 2014 11:28:16 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Apr 10, 2014 11:28:16 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
Apr 10, 2014 11:28:16 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Apr 10, 2014 11:28:16 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Apr 10, 2014 11:28:16 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Apr 10, 2014 11:28:16 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Apr 10, 2014 11:28:16 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Apr 10, 2014 11:28:16 PM org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator initiateService
WARN: HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections
Initial SessionFactory creation failed.org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.hibernate.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:20)
at org.hibernate.util.HibernateUtil.<clinit>(HibernateUtil.java:9)
at org.hibernate.Hibernate.main(Hibernate.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: 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:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at org.hibernate.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:14)
... 7 more
Process finished with exit code 1 |
|
Что используется: Java 7, Hibernate 4.3.5, PostgreSQL-jdbc-9.3-1101, Idea 13.1
Я понимаю, что ошибка конкретно в
Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set, но я же в конфиге указал диалект. Почему падает?
И второй вопрос: можно ли как-то промапить класс UserDetails без использования файла xml?
Добавлено через 23 часа 28 минут
Долго я еще ковырялся пока не нашел ответ. В итоге ошибка оказалась в файле HibernateUtil.java. Создание SessionFactory надо было делать так:
| Java |
1
2
3
4
5
6
7
8
9
10
11
12
| try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure("/hibernate.cfg.xml").buildSessionFactory(
new StandardServiceRegistryBuilder().applySettings(
new Configuration().configure("/hibernate.cfg.xml").getProperties()).build());
}
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);
} |
|
Разница лишь в том, что для StandardServiceRegistryBuilder не задавались конфиги и поэтому Hibernate не видел нужное ему. Там можно переписать все это в другом стиле (под спойлером), чтобы 2 раза не создавать Configuration.
что-то в таком стиле
| Java |
1
2
3
4
5
6
| Configuration configuration = new Configuration();
configuration.configure("/hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry); |
|
В ответ на вопрос можно ли не конфигурировать класс в xml ответ - можно. Насколько я понял для этого достаточно в hibernate.cfg.xml указать mapping class с путем к классу, а в самом классе с помощью аннотаций указать все для работы Hibernate.
Надеюсь кому-то ответ поможет. Я лишний раз убедился, что верить документации и всяким учебникам стоит очень придирчиво.