Форум программистов, компьютерный форум, киберфорум
Наши страницы
Java EE (J2EE)
Войти
Регистрация
Восстановить пароль
 
Nicolazz
1 / 1 / 2
Регистрация: 10.11.2011
Сообщений: 83
#1

Создать SessionFactory (Hibernate HelloWorld) - Java EE

23.07.2016, 14:14. Просмотров 1244. Ответов 4
Метки нет (Все метки)

Мне вообще кажется, что я что-то не так подключил. Идея видит БД, даже список баз, а дальше вот это вот.

Зависимости:
Java
1
2
3
4
    <properties>
        <hibernate.version>5.2.1.Final</hibernate.version>
        <mysql-connector-java>6.0.3</mysql-connector-java>
    </properties>
Создание SessionFactory:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class HibernateUtil {
    private static SessionFactory sessionFactory;
 
    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            // loads configuration and mappings
            Configuration configuration = new Configuration().configure();
            ServiceRegistry serviceRegistry
                    = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();
 
            // builds a session factory from the service registry
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);//тут ошибка Unable to create requested service
        }
 
        return sessionFactory;
    }
}
Main:
Java
1
2
3
4
5
6
public class Main {
    public static void main(String[] args) {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        System.out.printf("");
    }
}
Вывод консоли:
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
июл 23, 2016 2:06:07 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.1.Final}
июл 23, 2016 2:06:09 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
июл 23, 2016 2:06:09 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
июл 23, 2016 2:06:11 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
июл 23, 2016 2:06:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
июл 23, 2016 2:06:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/test]
июл 23, 2016 2:06:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
июл 23, 2016 2:06:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
июл 23, 2016 2:06:11 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:264)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:228)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
    at HibernateUtil.getSessionFactory(HibernateUtil.java:18)
    at Main.main(Main.java:5)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:105)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:123)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:41)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:58)
    at org.hibernate.engine.jdbc.connections.internal.PooledConnections.addConnections(PooledConnections.java:106)
    at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:40)
    at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:19)
    at org.hibernate.engine.jdbc.connections.internal.PooledConnections$Builder.build(PooledConnections.java:138)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:110)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:74)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:254)
    ... 19 more
Caused by: java.sql.SQLException: The server time zone value 'MSK' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:695)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:663)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:653)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:638)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:606)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:624)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:620)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:69)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1663)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:662)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:352)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:221)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
    ... 34 more
Caused by: com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: The server time zone value 'MSK' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:54)
    at com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:73)
    at com.mysql.cj.jdbc.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:118)
    at com.mysql.cj.mysqla.MysqlaSession.configureTimezone(MysqlaSession.java:315)
    at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:2446)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1797)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1653)
    ... 38 more
 
Process finished with exit code 1

http://www.cyberforum.ru/java-j2ee/thread894724.html
0
Лучшие ответы (1)
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
Similar
Эксперт
41792 / 34177 / 6122
Регистрация: 12.04.2006
Сообщений: 57,940
23.07.2016, 14:14
Я подобрал для вас темы с готовыми решениями и ответами на вопрос Создать SessionFactory (Hibernate HelloWorld) (Java EE):

Servlet Hibernate (SessionFactory) ошибка
Есть файл HibernateUtils package DB.utils; import...

Spring + Hibernate | Error creating bean with name 'sessionFactory'
Относительно недавно начал изучение Java. При создании веб-приложения при...

Spring mvc, hibernate, mysql: sessionFactory забивает базу подключениями
При вызове метода из SupplierDAOImpl в базу добавляются 10 подключений...

Невозможно создать объект SessionFactory (java.lang.ExceptionInInitializerError)
Вот класс который отвечает за создание этого объекта: public class...

Создать таблицу в БД средствами Hibernate
Есть зависимости &lt;properties&gt; ...

4
ninjacut
149 / 149 / 51
Регистрация: 30.04.2016
Сообщений: 321
23.07.2016, 14:29 #2
Caused by: com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: The server time zone value 'MSK' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
1
KEKCoGEN
Эксперт Java
2037 / 1912 / 494
Регистрация: 28.12.2010
Сообщений: 7,656
23.07.2016, 14:29 #3
Nicolazz, com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: The server time zone value 'MSK' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support

говорят что это баг в коннекторе. Поменяйте версию коннектора на 5.1.39
1
Nicolazz
1 / 1 / 2
Регистрация: 10.11.2011
Сообщений: 83
23.07.2016, 14:41  [ТС] #4
Спасибо, что-то создалось!

Добавлено через 2 минуты
Выдаёт вот это и виснет. Так и должно быть? Закрутилось на сервере и всё?

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/usr/lib/jvm/java-8-oracle/bin/java -Didea.launcher.port=7534 -Didea.launcher.bin.path=/opt/idea-IU-162.1121.32/bin -Dfile.encoding=UTF-8 -classpath /usr/lib/jvm/java-8-oracle/jre/lib/charsets.jar:/usr/lib/jvm/java-8-oracle/jre/lib/deploy.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/cldrdata.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/dnsns.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/jaccess.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/jfxrt.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/localedata.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/nashorn.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunec.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunjce_provider.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunpkcs11.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/zipfs.jar:/usr/lib/jvm/java-8-oracle/jre/lib/javaws.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jce.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jfr.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jfxswt.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jsse.jar:/usr/lib/jvm/java-8-oracle/jre/lib/management-agent.jar:/usr/lib/jvm/java-8-oracle/jre/lib/plugin.jar:/usr/lib/jvm/java-8-oracle/jre/lib/resources.jar:/usr/lib/jvm/java-8-oracle/jre/lib/rt.jar:/home/nicolas/dev/projects/TopJava/HiberTest/target/classes:/home/nicolas/.m2/repository/org/hibernate/hibernate-core/5.2.1.Final/hibernate-core-5.2.1.Final.jar:/home/nicolas/.m2/repository/org/jboss/logging/jboss-logging/3.3.0.Final/jboss-logging-3.3.0.Final.jar:/home/nicolas/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar:/home/nicolas/.m2/repository/org/javassist/javassist/3.20.0-GA/javassist-3.20.0-GA.jar:/home/nicolas/.m2/repository/antlr/antlr/2.7.7/antlr-2.7.7.jar:/home/nicolas/.m2/repository/org/apache/geronimo/specs/geronimo-jta_1.1_spec/1.1.1/geronimo-jta_1.1_spec-1.1.1.jar:/home/nicolas/.m2/repository/org/jboss/jandex/2.0.0.Final/jandex-2.0.0.Final.jar:/home/nicolas/.m2/repository/com/fasterxml/classmate/1.3.0/classmate-1.3.0.jar:/home/nicolas/.m2/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar:/home/nicolas/.m2/repository/org/hibernate/common/hibernate-commons-annotations/5.0.1.Final/hibernate-commons-annotations-5.0.1.Final.jar:/home/nicolas/.m2/repository/javax/enterprise/cdi-api/1.1-PFD/cdi-api-1.1-PFD.jar:/home/nicolas/.m2/repository/javax/el/el-api/2.2/el-api-2.2.jar:/home/nicolas/.m2/repository/org/jboss/spec/javax/interceptor/jboss-interceptors-api_1.1_spec/1.0.0.Beta1/jboss-interceptors-api_1.1_spec-1.0.0.Beta1.jar:/home/nicolas/.m2/repository/javax/annotation/jsr250-api/1.0/jsr250-api-1.0.jar:/home/nicolas/.m2/repository/javax/inject/javax.inject/1/javax.inject-1.jar:/home/nicolas/.m2/repository/org/hibernate/hibernate-entitymanager/5.2.1.Final/hibernate-entitymanager-5.2.1.Final.jar:/home/nicolas/.m2/repository/org/hibernate/hibernate-validator/5.2.1.Final/hibernate-validator-5.2.1.Final.jar:/home/nicolas/.m2/repository/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar:/home/nicolas/.m2/repository/mysql/mysql-connector-java/5.1.39/mysql-connector-java-5.1.39.jar:/opt/idea-IU-162.1121.32/lib/idea_rt.jar com.intellij.rt.execution.application.AppMain Main
июл 23, 2016 2:38:51 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.1.Final}
июл 23, 2016 2:38:51 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
июл 23, 2016 2:38:51 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
июл 23, 2016 2:38:51 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
июл 23, 2016 2:38:51 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
июл 23, 2016 2:38:51 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/test]
июл 23, 2016 2:38:51 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
июл 23, 2016 2:38:51 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
июл 23, 2016 2:38:51 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
июл 23, 2016 2:38:52 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
июл 23, 2016 2:38:52 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 5.2.1.Final
0
KEKCoGEN
Эксперт Java
2037 / 1912 / 494
Регистрация: 28.12.2010
Сообщений: 7,656
23.07.2016, 14:58 #5
Лучший ответ Сообщение было отмечено Nicolazz как решение

Решение

Nicolazz, что значит виснет? В логе ошибок нет. Все поднялось как надо.
1
23.07.2016, 14:58
MoreAnswers
Эксперт
37091 / 29110 / 5898
Регистрация: 17.06.2006
Сообщений: 43,301
23.07.2016, 14:58
Привет! Вот еще темы с решениями:

Hibernate - получение информации о маппинге из Configuration (SessionFactory)
Есть Configuration (или созданный по нему SessionFactory), инциализированный...

HelloWorld не работает: Exception in thread 'main' java.lang.NoClassDefFoundError: HelloWorld.
Что за ерунда - не пойму. Установил последний NetBeans и JDK 1.3.1 Взял...

Hibernate Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
Доброго времени суток. Сталкиваюсь со всякими ошибками при добавлении данных в...

Почему Hibernate пытается создать сущность с нулевым id?
Здравствуйте. Помогите, пожалуйста, решить проблему. Написал приложение для...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin® Version 3.8.9
Copyright ©2000 - 2018, vBulletin Solutions, Inc.
Рейтинг@Mail.ru