Hibernate exception in creating a table - java

Please help me figure out the reason of this exception and how to resolve it.
Following a youtube tutorial, I am trying to create a table named 'alien' in a MySQL database named 'abc'. I am using the Hibernate ORM tool and Maven for this but Hibernate is throwing an exception
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table Alien (stud_id integer not null, age integer not null, marks integer not null, stud_name varchar(255), primary key (stud_id)) type=MyISAM" via JDBC Statement
Here is the complete stack trace:
"C:\Program Files\Java\jdk-14.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2020.2\lib\idea_rt.jar=57063:C:\Program Files\JetBrains\IntelliJ IDEA 2020.2\bin" -Dfile.encoding=UTF-8 -classpath D:\BITS\Practice-School-2\Training\HibernateDemo\target\classes;C:\Users\shshw\.m2\repository\org\hibernate\hibernate-core\5.4.20.Final\hibernate-core-5.4.20.Final.jar;C:\Users\shshw\.m2\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;C:\Users\shshw\.m2\repository\javax\persistence\javax.persistence-api\2.2\javax.persistence-api-2.2.jar;C:\Users\shshw\.m2\repository\org\javassist\javassist\3.24.0-GA\javassist-3.24.0-GA.jar;C:\Users\shshw\.m2\repository\net\bytebuddy\byte-buddy\1.10.10\byte-buddy-1.10.10.jar;C:\Users\shshw\.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Users\shshw\.m2\repository\org\jboss\spec\javax\transaction\jboss-transaction-api_1.2_spec\1.1.1.Final\jboss-transaction-api_1.2_spec-1.1.1.Final.jar;C:\Users\shshw\.m2\repository\org\jboss\jandex\2.1.3.Final\jandex-2.1.3.Final.jar;C:\Users\shshw\.m2\repository\com\fasterxml\classmate\1.5.1\classmate-1.5.1.jar;C:\Users\shshw\.m2\repository\javax\activation\javax.activation-api\1.2.0\javax.activation-api-1.2.0.jar;C:\Users\shshw\.m2\repository\org\dom4j\dom4j\2.1.3\dom4j-2.1.3.jar;C:\Users\shshw\.m2\repository\org\hibernate\common\hibernate-commons-annotations\5.1.0.Final\hibernate-commons-annotations-5.1.0.Final.jar;C:\Users\shshw\.m2\repository\javax\xml\bind\jaxb-api\2.3.1\jaxb-api-2.3.1.jar;C:\Users\shshw\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.1\jaxb-runtime-2.3.1.jar;C:\Users\shshw\.m2\repository\org\glassfish\jaxb\txw2\2.3.1\txw2-2.3.1.jar;C:\Users\shshw\.m2\repository\com\sun\istack\istack-commons-runtime\3.0.7\istack-commons-runtime-3.0.7.jar;C:\Users\shshw\.m2\repository\org\jvnet\staxex\stax-ex\1.8\stax-ex-1.8.jar;C:\Users\shshw\.m2\repository\com\sun\xml\fastinfoset\FastInfoset\1.2.15\FastInfoset-1.2.15.jar;C:\Users\shshw\.m2\repository\mysql\mysql-connector-java\8.0.21\mysql-connector-java-8.0.21.jar;C:\Users\shshw\.m2\repository\com\google\protobuf\protobuf-java\3.11.4\protobuf-java-3.11.4.jar com.Telusko.App
Aug 27, 2020 9:35:24 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.4.20.Final
Aug 27, 2020 9:35:25 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
Aug 27, 2020 9:35:25 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Aug 27, 2020 9:35:25 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/abc]
Aug 27, 2020 9:35:25 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=root}
Aug 27, 2020 9:35:25 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Aug 27, 2020 9:35:25 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Aug 27, 2020 9:35:25 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 27, 2020 9:35:26 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#380e1909] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Aug 27, 2020 9:35:26 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error executing DDL "create table Alien (stud_id integer not null, age integer not null, marks integer not null, stud_name varchar(255), primary key (stud_id)) type=MyISAM" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table Alien (stud_id integer not null, age integer not null, marks integer not null, stud_name varchar(255), primary key (stud_id)) type=MyISAM" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:277)
at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:71)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:207)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:316)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:469)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at com.Telusko.App.main(App.java:23)
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'type=MyISAM' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:764)
at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
... 13 more
Aug 27, 2020 9:35:26 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Aug 27, 2020 9:35:26 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1146, SQLState: 42S02
Aug 27, 2020 9:35:26 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Table 'abc.alien' doesn't exist
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1367)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:454)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3213)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2381)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
at com.Telusko.App.main(App.java:28)
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3255)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3782)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:107)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478)
at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:723)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1363)
... 9 more
Caused by: java.sql.SQLSyntaxErrorException: Table 'abc.alien' doesn't exist
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1347)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)
... 20 more
Process finished with exit code 1
Here is the POJO/Entity for the table to be created:
package com.Telusko;
//POJO- Plain Old Java Object
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Alien {
#Id
int stud_id;
String stud_name;
int marks;
int age;
public int getStud_id() {
return stud_id;
}
public void setStud_id(int stud_id) {
this.stud_id = stud_id;
}
public String getStud_name() {
return stud_name;
}
public void setStud_name(String stud_name) {
this.stud_name = stud_name;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Here is the pom.xml file for the Maven project:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.Telusko</groupId>
<artifactId>HibernateDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<name>HibernateDemo</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.20.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
The hibernate.cfg.xml file:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/abc</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">update</property>
<!-- <property name="hibernate.connection.autocommit">True</property>-->
<!-- <property name="connection.username"/> -->
<!-- <property name="connection.password"/> -->
<!-- DB schema will be updated if needed -->
<!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
The main class file:
package com.Telusko;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class App
{
public static void main( String[] args )
{
Alien alien = new Alien();
alien.setStud_id(101);
alien.setStud_name("Navin");
alien.setMarks(67);
alien.setAge(22);
Configuration configuration = new Configuration().configure().addAnnotatedClass(Alien.class);
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(alien);
transaction.commit();
System.out.println( "Hello World!" );
}
}

In your persistence.cfg.xml file you should change the dialect to: org.hibernate.dialect.MySQL5InnoDBDialect
Or you can simply remove it, Hibernate should be able to detect it automatically
This should let Hibernate create InnoDB tables instead of MyISAM

Try using different dialects, if you are using MySQL v8 then use these dialects org.hibernate.dialect.MySQL8Dialect or com.mysql.cj.jdbc.Driver
error is with the dialect, you can check its generating type=MyISAM instead it should be ENGINE=MyISAM
type is deprecated from MySQL version 5, ENGINE is replaced from that version, since you are using MySQL8 dependency you need to use ENGINE
so the query should like this
create table Alien (columns names) Engine=MyISAM
use InnoDB engine instead of MyISAM
try executing the query in the console or workbench

Related

Error hibernate could not connect with mysql database

Description
basically i want to implement ORM using Hibernate with mysql 8.0.23 CE, for the creation of the
table i have configured it in the hibernate config file to be created:
but i'm encountered with the problem of "Could not create connection to database server"
as seen in the photos!
Entity
the representation of the table in mysql
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class User {
#Id
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Hibernate config file
<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">user</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/users</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
</session-factory>
CONSOLE LOG
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
atjava.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance
(NativeConstructorAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance
(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:917)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2332)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2085)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance
(NativeConstructorAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance
(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:400)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:327)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:189)
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl
.getConnection
(DriverManagerConnectionProviderImpl.java:193)
at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare
(SuppliedConnectionProviderConnectionHelper.java:51)
at org.hibernate.tool.hbm2ddl.DatabaseExporter.<init>(DatabaseExporter.java:52)
at org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:367)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:304)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:293)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:487)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1746)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1784)
at com.hibernate.Orm.App.main(App.java:16)
Caused by: java.lang.NullPointerException:
Cannot invoke "java.util.Map.get(Object)" because "this.serverVariables" is null
at com.mysql.jdbc.ConnectionImpl.getServerCharset(ConnectionImpl.java:3005)
at com.mysql.jdbc.MysqlIO.sendConnectionAttributes(MysqlIO.java:1916)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1845)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1215)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2255)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2286)
... 23 more
Mar 31, 2021 1:12:32 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Wed Mar 31 01:12:32 WEST 2021 WARN: Establishing SSL connection without server's identity
verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL
connection must be established by default if explicit option isn't set. For compliance with
existing applications not using SSL the verifyServerCertificate property is set to 'false'. You
need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide
truststore for server certificate verification.
Mar 31, 2021 1:12:32 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 08001
Mar 31, 2021 1:12:32 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Could not create connection to database server.
and more...
basically i want to implement ORM using Hibernate with mysql 8.0.23 CE, for the creation of the
table i have configured it in the hibernate config file to be created:
but i'm encountered with the problem of "Could not create connection to database server"
as seen in the photos!
POM
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hibernate</groupId>
<artifactId>hibernateOrm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.6.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
</dependencies>
</project>
basically i want to implement ORM using Hibernate with mysql 8.0.23 CE, for the creation of the
table i have configured it in the hibernate config file to be created:
but i'm encountered with the problem of "Could not create connection to database server"
as seen in the photos!
Main
package com.hibernate.Orm;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class App {
public static void main(String[] args) {
User user = new User();
user.setId(1);
user.setName("bruno");
Configuration config = new
Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(User.class);
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
session.save(user);
tx.commit();
session.close();
}
}
JARS USED
[1]: https://i.stack.imgur.com/3CbNu.png
Upgrade the java connector version with 5.1.46 minimum or above till latest 8.0.11 as old versions have issues with MySQL 8.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>

Maven Project Hibernate, MySQL connection problem

I am using Intelij idea and I am tying to make a simple connection with MySQL database with hibernate following a YouTube video.
For some reason my connection does not work and I get the following Errors:
Mar 30, 2021 12:04:31 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.4.30.Final
Mar 30, 2021 12:04:31 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Mar 30, 2021 12:04:31 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Mar 30, 2021 12:04:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Mar 30, 2021 12:04:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/calculator?autoReconnect=true&useSSL=false]
Mar 30, 2021 12:04:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=root}
Mar 30, 2021 12:04:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Mar 30, 2021 12:04:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Mar 30, 2021 12:04:36 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator initiateService
WARN: HHH000342: Could not obtain connection to query metadata
java.lang.IllegalStateException: Cannot get a connection as the driver manager is not properly initialized
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:172)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:107)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:246)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:116)
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.DriverManagerConnectionProviderImpl$PooledConnections.addConnections(DriverManagerConnectionProviderImpl.java:341)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.<init>(DriverManagerConnectionProviderImpl.java:260)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.<init>(DriverManagerConnectionProviderImpl.java:238)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections$Builder.build(DriverManagerConnectionProviderImpl.java:379)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:98)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:73)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:107)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:246)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
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:101)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:176)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:127)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:86)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:479)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:85)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:689)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at org.example.App.main(App.java:25)
Mar 30, 2021 12:04:36 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Mar 30, 2021 12:04:36 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 08001
Mar 30, 2021 12:04:36 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Hello World!
Process finished with exit code 0
I am using zulu16.28.11 as my JDk, and MySQL WorkBench 8 .
From Idea I tested my connections and seems okay
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>DemoHib</artifactId>
<version>1.0-SNAPSHOT</version>
<name>DemoHib</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.30.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
hibernate.cfg.xml
<?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">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/calculator?autoReconnect=true&useSSL=false</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
</session-factory>
</hibernate-configuration>
Alien.java (my class)
package org.example;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Alien {
#Id
private int aid;
private String name;
private String pass;
public int getAid() {
return aid;
}
public String getName() {
return name;
}
public String getPass() {
return pass;
}
public void setAid(int aid) {
this.aid = aid;
}
public void setName(String name) {
this.name = name;
}
public void setPass(String pass) {
this.pass = pass;
}
}
App.java
package org.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class App
{
public static void main( String[] args )
{
Alien telusko = new Alien();
telusko.setAid(101);
telusko.setName("Matheos");
telusko.setPass("564");
Configuration con = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Alien.class);
try{
SessionFactory sf = con.buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
session.save(telusko);
tx.commit();
}
catch (Exception e){
System.out.println(e);
}
//SessionFactory sf = con.buildSessionFactory();
System.out.println( "Hello World!" );
}
}
I tried to find a solution for my problem online but I didnt find something to apply to my problem.
My problem was with the MySQL dependency I changed it to version 8.0.16 and worked.
I had this problem today too, I upgraded the package of mysql-connector-java for 8.0.23 and it worked fine.

Getting Hazelcast Native Client working with Hibernate 5.2.x

I'm trying to get Hazelcast working with Hibernate, but unless i use the super_client option, it doesn't start up.
According to the docs, Super Client should only be used if your app is on the same RAC or data center. For local, this will be the case, for production, they will most definitely be separated, so Native Client is the only option that will work for us.
Super Client is a member of the cluster, it has socket connection to
every member in the cluster and it knows where the data is so it will
get to the data much faster. But Super Client has the clustering
overhead and it must be on the same data center even on the same RAC.
However Native client is not member and relies on one of the cluster
members. Native Clients can be anywhere in the LAN or WAN. It scales
much better and overhead is quite less. So if your clients are less
than Hazelcast nodes then Super client can be an option; otherwise
definitely try Native Client. As a rule of thumb: Try Native client
first, if it doesn't perform well enough for you, then consider Super
client.
The best option for starting up Hazelcast seems to be using Docker:
docker pull hazelcast/hazelcast:3.10.4
docker run --name=hazelcast -d=true -p 5701:5701 hazelcast/hazelcast:3.10.4
And this is what it looks like once it is up and running, i double checked that the Hazelcast port, 5701, is exposed which it clearly is.
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
77a5a0bed5eb hazelcast/hazelcast:3.10.4 "bash -c 'set -euo p…" 3 days ago Up 6 hours 0.0.0.0:5701->5701/tcp hazelcast
The docker hub docs also mentions how to pass in JAVA_OPTS, i'm not sure if this is required or optional and what its purpose is, but this didn't help me get up and running:
-e JAVA_OPTS="-Dhazelcast.local.publicAddress=127.0.0.1:5701"
telnet 127.0.0.1 5701 successfully connects to localhost:5701, so i know the port is open. The docker docs doesn't mention what the default password is for this running Hazelcast instance, my assumption is that it's empty or that the password is dev-pass as mentioned in several older tutorials.
I'm using Hibernate 5.2.13.Final
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
<exclusions>
<exclusion>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
</exclusion>
<exclusion>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
<version>${hibernate.version}</version>
</dependency>
For Hazelcast, according to the docs, two dependencies are required,
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
<version>3.10.4</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-hibernate52</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-client</artifactId>
<version>3.10.4</version>
</dependency>
The docs show the following links:
Clicking Hibernate 5 shows that hazelcast-hibernate52 is the correct dependency
When i click See here for details, i'm greeted with docs that look somewhat outdated:
Assuming there's only a typo, i go through to the example:
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">false</property>
<property name="hibernate.cache.use_minimal_puts">true</property>
<property name="hibernate.cache.region.factory_class">com.hazelcast.hibernate.HazelcastCacheRegionFactory</property>
<property name="hibernate.cache.hazelcast.use_native_client">false</property>
<property name="hibernate.cache.hazelcast.native_client_hosts">127.0.0.1</property>
<property name="hibernate.cache.hazelcast.native_client_group">hibernate</property>
<property name="hibernate.cache.hazelcast.native_client_password">password</property>
<property name="hibernate.connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property>
<property name="hibernate.connection.url">jdbc:derby:hibernateDB</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
In the example, Use Native Client is set to false, yet it is being configured, is this a typo or is this the correct configuration?
I'm trying out these settings on a standard Hibernate Postgres with C3P0 setup, here's my persistence.xml
<properties>
<!-- Hibernate Config -->
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL95Dialect" />
<property name="hibernate.generate_statistics" value="false" />
<property name="hibernate.hbm2ddl.auto" value="validate"/>
<property name="hibernate.physical_naming_strategy" value="za.co.convirt.util.CustomApplicationNamingStrategy"/>
<property name="hibernate.connection.charSet" value="UTF-8"/>
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="false"/>
<property name="hibernate.use_sql_comments" value="false"/>
<!-- JDBC Config -->
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.time_zone" value="UTC" />
<property name="hibernate.jdbc.time_zone" value="UTC"/>
<!-- Connection Pool -->
<property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider" />
<property name="hibernate.c3p0.max_size" value="5" />
<property name="hibernate.c3p0.min_size" value="1" />
<property name="hibernate.c3p0.acquire_increment" value="1" />
<property name="hibernate.c3p0.idle_test_period" value="300" />
<property name="hibernate.c3p0.max_statements" value="0" />
<property name="hibernate.c3p0.timeout" value="100" />
<!-- Batch writing -->
<property name="hibernate.jdbc.batch_size" value = "50"/>
<property name="hibernate.order_updates" value = "true"/>
<property name="hibernate.jdbc.batch_versioned_data" value = "true"/>
</properties>
Some params are entered programmatically via (this has been in use for ages, so i know it works, but adding it here just in case it helps make the code more clear)
fun paramsFromArgs(args: Array<String>): Map<String, String> {
val hibernateMap = mutableMapOf<String, String>()
args.forEach {
if (it.isNotBlank()) {
if (it.startsWith("hibernate") || it.startsWith("javax.persistence")) {
val split = it.split("=", limit = 2)
hibernateMap.put(split.get(0), split.get(1))
}
}
}
return hibernateMap
}
Now when i setup Second Level cache with Hazelcast:
paramsDefault.add("hibernate.cache.use_query_cache=true")
paramsDefault.add("hibernate.cache.use_second_level_cache=true")
paramsDefault.add("hibernate.cache.region.factory_class=com.hazelcast.hibernate.HazelcastCacheRegionFactory")
paramsDefault.add("hibernate.cache.provider_configuration_file_resource_path=hazelcast.xml")
paramsDefault.add("hibernate.cache.hazelcast.use_native_client=false")
paramsDefault.add("hibernate.cache.hazelcast.native_client_address=127.0.0.1")
paramsDefault.add("hibernate.cache.hazelcast.native_client_group=dev")
paramsDefault.add("hibernate.cache.hazelcast.native_client_password=dev-pass22222asfasdf")
paramsDefault.add("hibernate.cache.hazelcast.client.statistics.enabled=true")
Database.setupEntityManagerFactory("default",
Database.paramsFromArgs(paramsDefault.toTypedArray()))
Setting use_native_client to false like in the example doesn't seem to do anything, with the logs in debug mode, i'm not seeing anything Hazelcast related.
Switching it to true (which makes more sense considering it's being configured to have a password and IP address, it bombs out on startup.
hibernate.cache.hazelcast.use_native_client=true
hibernate.cache.hazelcast.native_client_address=127.0.0.1
hibernate.cache.hazelcast.native_client_group=dev
hibernate.cache.hazelcast.native_client_password=dev-pass
DEB [16:18:26.531] setup org.hibernate.jpa.internal.util.LogHelper PersistenceUnitInfo [
name: default
persistence provider classname: org.hibernate.jpa.HibernatePersistenceProvider
classloader: null
excludeUnlistedClasses: false
JTA datasource: null
Non JTA datasource: null
Transaction type: RESOURCE_LOCAL
PU root URL: file:/Users/vlad/Code/.../...
Shared Cache Mode: null
Validation Mode: null
Jar files URLs []
Managed classes names []
Mapping files names []
Properties [
...
hibernate.jdbc.time_zone: UTC
javax.persistence.jdbc.password:
hibernate.cache.region.factory_class: com.hazelcast.hibernate.HazelcastCacheRegionFactory
hibernate.c3p0.idle_test_period: 300
hibernate.cache.hazelcast.use_native_client: true
...
hibernate.cache.hazelcast.native_client_group: dev
...
javax.persistence.jdbc.driver: org.postgresql.Driver
hibernate.use_sql_comments: false
hibernate.cache.hazelcast.native_client_address: 127.0.0.1
...
hibernate.cache.hazelcast.client.statistics.enabled: true
hibernate.dialect: org.hibernate.dialect.PostgreSQL95Dialect
hibernate.cache.provider_configuration_file_resource_path: hazelcast.xml]
HazelcastCacheRegionFactory is being used according to the logs:
DEB [16:18:26.884] setup org.hibernate.cache.internal.RegionFactoryInitiator
Cache region factory : com.hazelcast.hibernate.HazelcastCacheRegionFactory
Followed by two log entries that doesn't follow my logging standard (i'm guessing it's not using SLF4j?):
Sep 12, 2018 2:18:29 PM com.hazelcast.hibernate.HazelcastCacheRegionFactory
INFO: Starting up HazelcastCacheRegionFactory
... and then Unable to build Hibernate Session Factory:
ERR [16:18:29.802] setup ApplicationApi [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException (EntityManagerFactoryBuilderImpl.java:970)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build (EntityManagerFactoryBuilderImpl.java:895)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory (HibernatePersistenceProvider.java:58)
at javax.persistence.Persistence.createEntityManagerFactory (Persistence.java:55)
at za.co.convirt.util.Database.setupEntityManagerFactory (Database.kt:20)
at za.co.convirt.util.Database.setupEntityManagerFactory$default (Database.kt:19)
at ApplicationApi$main$hibernateThread$1.invoke (ApplicationApi.kt:171)
at ApplicationApi$main$hibernateThread$1.invoke (ApplicationApi.kt:26)
at kotlin.concurrent.ThreadsKt$thread$thread$1.run (Thread.kt:30)
To make sure that it's not failing due to missing annotations on entities, i added a few #Cache annotations to entities, but it makes no difference.
#Table
#Entity
#EntityListeners(AuditListener::class)
#PersistenceContext(unitName = "default")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Seat")
class Seat(
name: String,
...
I've also added a hazelcast.xml, not sure if this is needed or not:
<hazelcast
xmlns="http://www.hazelcast.com/schema/config"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.hazelcast.com/schema/config
http://www.hazelcast.com/schema/config/hazelcast-config-3.11.xsd">
<services enable-defaults="true"/>
</hazelcast>
Is hibernate 5.2.x supported? (this ticket shows that the problems with Hibernate 5.2 was fixed, so my assumption is that it should work)
I want to run a stand-alone Hazelcast instance on one server and have multiple instances of the application use it as a central cache location, what am i missing from setup to make it work?
Update 1:
I've written a small piece of code that successfully connects to the local hazelcast instance (this is on my dev machine, same as with the rest of the code)
import com.hazelcast.client.HazelcastClient
import com.hazelcast.client.config.ClientConfig
import java.util.*
fun main(args: Array<String>) {
val config = ClientConfig()
config.getNetworkConfig().addAddress("127.0.0.1:5701")
val hazelcastInstance = HazelcastClient.newHazelcastClient(config)
val map = hazelcastInstance.getMap<String, String>("blah")
map.forEach { t, u ->
println(" $t -> $u ")
}
map.put("${Random().nextInt()}", "${Random().nextInt()}")
hazelcastInstance.shutdown()
}
To proof that it's storing and retrieving from cache, i restart the main method several times and each time the number of entries in blah increases
Run1:
No printlns
Run2:
1498523740 -> -1418154711
Run3:
1498523740 -> -1418154711
-248583979 -> -940621527
So Hazelcast is working correctly ...
Update 2:
I can now connect hazelcast from Hibernate, but it's throwing an exception for every lookup it has to do.
Removing hazelcast.xml from my classpath and then removing the group and password options, Hibernate is starting up and connecting.
paramsDefault.add("hibernate.cache.use_query_cache=true")
paramsDefault.add("hibernate.cache.use_second_level_cache=true")
paramsDefault.add("hibernate.cache.region.factory_class=com.hazelcast.hibernate.HazelcastCacheRegionFactory")
paramsDefault.add("hibernate.cache.hazelcast.use_native_client=true")
paramsDefault.add("hibernate.cache.hazelcast.native_client_address=127.0.0.1")
Outputs:
Sep 13, 2018 6:02:37 PM com.hazelcast.hibernate.HazelcastCacheRegionFactory
INFO: Starting up HazelcastCacheRegionFactory
Sep 13, 2018 6:02:37 PM com.hazelcast.core.LifecycleService
INFO: hz.client_0 [dev] [3.10.4] HazelcastClient 3.10.4 (20180727 - 0f51fcf) is STARTING
Sep 13, 2018 6:02:38 PM com.hazelcast.client.spi.ClientInvocationService
INFO: hz.client_0 [dev] [3.10.4] Running with 2 response threads
Sep 13, 2018 6:02:38 PM com.hazelcast.core.LifecycleService
INFO: hz.client_0 [dev] [3.10.4] HazelcastClient 3.10.4 (20180727 - 0f51fcf) is STARTED
Sep 13, 2018 6:02:38 PM com.hazelcast.client.connection.ClientConnectionManager
INFO: hz.client_0 [dev] [3.10.4] Trying to connect to [127.0.0.1]:5701 as owner member
Sep 13, 2018 6:02:38 PM com.hazelcast.client.connection.ClientConnectionManager
INFO: hz.client_0 [dev] [3.10.4] Setting ClientConnection{alive=true, connectionId=1, channel=NioChannel{/127.0.0.1:61191->/127.0.0.1:5701}, remoteEndpoint=[127.0.0.1]:5701, lastReadTime=2018-09-13 18:02:38.356, lastWriteTime=2018-09-13 18:02:38.352, closedTime=never, lastHeartbeatRequested=never, lastHeartbeatReceived=never, connected server version=3.10.4} as owner with principal ClientPrincipal{uuid='532bf500-e03e-4620-a9c2-14bb55c07166', ownerUuid='2fb66fa1-a17f-49fe-ba2b-bf585d43906d'}
Sep 13, 2018 6:02:38 PM com.hazelcast.client.connection.ClientConnectionManager
INFO: hz.client_0 [dev] [3.10.4] Authenticated with server [127.0.0.1]:5701, server version:3.10.4 Local address: /127.0.0.1:61191
Sep 13, 2018 6:02:38 PM com.hazelcast.client.spi.impl.ClientMembershipListener
INFO: hz.client_0 [dev] [3.10.4]
Members [1] {
Member [127.0.0.1]:5701 - 2fb66fa1-a17f-49fe-ba2b-bf585d43906d
}
Sep 13, 2018 6:02:38 PM com.hazelcast.core.LifecycleService
INFO: hz.client_0 [dev] [3.10.4] HazelcastClient 3.10.4 (20180727 - 0f51fcf) is CLIENT_CONNECTED
Sep 13, 2018 6:02:38 PM com.hazelcast.internal.diagnostics.Diagnostics
INFO: hz.client_0 [dev] [3.10.4] Diagnostics disabled. To enable add -Dhazelcast.diagnostics.enabled=true to the JVM arguments.
However, any entity that's being retrieved that makes a call to Hazelcast, just stalls.
I've restarted Hazelcast with JAVA_OPTS to see if it makes a different, doesn't seem like it:
docker run --name=hazelcast -d=true -p 5701:5701 -e JAVA_OPTS="-Dhazelcast.local.publicAddress=127.0.0.1:5701" hazelcast/hazelcast:3.10.4
Digging into Hazelcast logs using:
docker logs -f hazelcast
I'm seeing the following:
Sep 13, 2018 6:02:11 PM com.hazelcast.client.ClientEndpointManager
INFO: [127.0.0.1]:5701 [dev] [3.10.4] Destroying ClientEndpoint{connection=Connection[id=2, /172.17.0.2:5701->/172.17.0.1:56514, endpoint=[172.17.0.1]:56514, alive=false, type=JAVA_CLIENT], principal='ClientPrincipal{uuid='d8a9b730-c5fd-458c-9ab6-671aece99305', ownerUuid='2fb66fa1-a17f-49fe-ba2b-bf585d43906d'}, ownerConnection=true, authenticated=true, clientVersion=3.10.4, creationTime=1536861657874, latest statistics=null}
Sep 13, 2018 6:02:38 PM com.hazelcast.nio.tcp.TcpIpAcceptor
INFO: [127.0.0.1]:5701 [dev] [3.10.4] Accepting socket connection from /172.17.0.1:56516
Sep 13, 2018 6:02:38 PM com.hazelcast.nio.tcp.TcpIpConnectionManager
INFO: [127.0.0.1]:5701 [dev] [3.10.4] Established socket connection between /172.17.0.2:5701 and /172.17.0.1:56516
Sep 13, 2018 6:02:38 PM com.hazelcast.client.impl.protocol.task.AuthenticationMessageTask
INFO: [127.0.0.1]:5701 [dev] [3.10.4] Received auth from Connection[id=3, /172.17.0.2:5701->/172.17.0.1:56516, endpoint=null, alive=true, type=JAVA_CLIENT], successfully authenticated, principal: ClientPrincipal{uuid='532bf500-e03e-4620-a9c2-14bb55c07166', ownerUuid='2fb66fa1-a17f-49fe-ba2b-bf585d43906d'}, owner connection: true, client version: 3.10.4
Sep 13, 2018 6:03:11 PM com.hazelcast.transaction.TransactionManagerService
INFO: [127.0.0.1]:5701 [dev] [3.10.4] Committing/rolling-back live transactions of client, UUID: d8a9b730-c5fd-458c-9ab6-671aece99305
Upon hitting the cache:
Sep 13, 2018 6:05:43 PM com.hazelcast.map.impl.operation.EntryOperation
SEVERE: [127.0.0.1]:5701 [dev] [3.10.4] java.lang.ClassNotFoundException: org.hibernate.cache.spi.entry.StandardCacheEntryImpl
com.hazelcast.nio.serialization.HazelcastSerializationException: java.lang.ClassNotFoundException: org.hibernate.cache.spi.entry.StandardCacheEntryImpl
at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.read(JavaDefaultSerializers.java:86)
at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.read(JavaDefaultSerializers.java:75)
at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.read(StreamSerializerAdapter.java:48)
at com.hazelcast.internal.serialization.impl.AbstractSerializationService.readObject(AbstractSerializationService.java:269)
at com.hazelcast.internal.serialization.impl.ByteArrayObjectDataInput.readObject(ByteArrayObjectDataInput.java:574)
at com.hazelcast.hibernate.serialization.Value.readData(Value.java:78)
at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.readInternal(DataSerializableSerializer.java:160)
at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.read(DataSerializableSerializer.java:106)
at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.read(DataSerializableSerializer.java:51)
at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.read(StreamSerializerAdapter.java:48)
at com.hazelcast.internal.serialization.impl.AbstractSerializationService.toObject(AbstractSerializationService.java:187)
at com.hazelcast.query.impl.CachedQueryEntry.getValue(CachedQueryEntry.java:75)
at com.hazelcast.hibernate.distributed.LockEntryProcessor.process(LockEntryProcessor.java:49)
at com.hazelcast.hibernate.distributed.LockEntryProcessor.process(LockEntryProcessor.java:32)
at com.hazelcast.map.impl.operation.EntryOperator.process(EntryOperator.java:319)
at com.hazelcast.map.impl.operation.EntryOperator.operateOnKeyValueInternal(EntryOperator.java:182)
at com.hazelcast.map.impl.operation.EntryOperator.operateOnKey(EntryOperator.java:167)
at com.hazelcast.map.impl.operation.EntryOperation.runVanilla(EntryOperation.java:384)
at com.hazelcast.map.impl.operation.EntryOperation.call(EntryOperation.java:188)
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.call(OperationRunnerImpl.java:202)
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:191)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationExecutorImpl.run(OperationExecutorImpl.java:406)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationExecutorImpl.runOrExecute(OperationExecutorImpl.java:433)
at com.hazelcast.spi.impl.operationservice.impl.Invocation.doInvokeLocal(Invocation.java:581)
at com.hazelcast.spi.impl.operationservice.impl.Invocation.doInvoke(Invocation.java:566)
at com.hazelcast.spi.impl.operationservice.impl.Invocation.invoke0(Invocation.java:525)
at com.hazelcast.spi.impl.operationservice.impl.Invocation.invoke(Invocation.java:215)
at com.hazelcast.spi.impl.operationservice.impl.InvocationBuilderImpl.invoke(InvocationBuilderImpl.java:60)
at com.hazelcast.client.impl.protocol.task.AbstractPartitionMessageTask.processMessage(AbstractPartitionMessageTask.java:67)
at com.hazelcast.client.impl.protocol.task.AbstractMessageTask.initializeAndProcessMessage(AbstractMessageTask.java:123)
at com.hazelcast.client.impl.protocol.task.AbstractMessageTask.doRun(AbstractMessageTask.java:111)
at com.hazelcast.client.impl.protocol.task.AbstractMessageTask.run(AbstractMessageTask.java:101)
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:155)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:125)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.run(OperationThread.java:100)
Caused by: java.lang.ClassNotFoundException: org.hibernate.cache.spi.entry.StandardCacheEntryImpl
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at com.hazelcast.nio.ClassLoaderUtil.tryLoadClass(ClassLoaderUtil.java:173)
at com.hazelcast.nio.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:147)
at com.hazelcast.nio.IOUtil$ClassLoaderAwareObjectInputStream.resolveClass(IOUtil.java:615)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1866)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1749)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2040)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1571)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.read(JavaDefaultSerializers.java:82)
... 34 more
Do i need to include some kind of JAR inside my Hazelcast Docker setup, or what is happening here?
Looks like you are attempting to use the loop back address from another sever and outside of the docker network.
You may want to try bridged to eliminate the docker network address translation.
Also since 0.0.0.0 is bonded thus all ip addresses should have Hazelcast listeners installed.
I would simplify and first validate Hazelcast. If you have enterprise then use the console application otherwise write a simple start server java main. And then attemp to connect with a client using a real IP address. Once this works then work on hibernate configuration.
Finally got it working, here's what was needed:
1: Make sure you have all three these dependencies, initially i was missing the first one, but for some reason, wasn't getting a ClassNotFound exception as expected. It doesn't seem to be a transitive dependency of either hazelcast-client or hazelcast-hibernate52
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
<version>${hazelcast.version}</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-hibernate52</artifactId>
<version>${hazelcast-hibernate.version}</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-client</artifactId>
<version>${hazelcast.version}</version>
</dependency>
2: If your dev instance of Hazelcast doesn't have a password, don't specify the password. 127.0.0.1 works fine, no need to run on an external server while dev-ing.
paramsDefault.add("hibernate.cache.use_query_cache=true")
paramsDefault.add("hibernate.cache.use_second_level_cache=true")
paramsDefault.add("hibernate.cache.region.factory_class=com.hazelcast.hibernate.HazelcastCacheRegionFactory")
paramsDefault.add("hibernate.cache.hazelcast.use_native_client=true")
paramsDefault.add("hibernate.cache.hazelcast.native_client_address=127.0.0.1")
// paramsDefault.add("hibernate.cache.hazelcast.native_client_group=$ENV")
// paramsDefault.add("hibernate.cache.hazelcast.native_client_password=dev-pass")
3: Get rid of hazelcast.xml - after removing that hazelcast.xml file, Hibernate actually started up even though my hazelcast.xml file just had a one-liner in it saying use default config.
4: Make sure all entities are marked with Serializable, otherwise entities won't cache and cause an exception on the Hazelcast server itself.
#Table
#Entity
#BatchSize(size = 50)
#PersistenceContext(unitName = "default")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Tag")
class Tag(
name: String,
) : Serializable {
5: If your entity has #OneToMany, #ManyToOne or other entities inside of it, make sure those entities are Serializable as well.
6: Write a little script to ensure that your entities are caching:
import com.hazelcast.client.HazelcastClient
import com.hazelcast.client.config.ClientConfig
fun main(args: Array<String>) {
val config = ClientConfig()
config.getNetworkConfig().addAddress("127.0.0.1:5701")
val hazelcastInstance = HazelcastClient.newHazelcastClient(config)
val map = hazelcastInstance.getMap<Any, Any>("Tag")
println("=================")
map.forEach { t, u ->
println(" $t -> $u ")
}
println("=================")
hazelcastInstance.shutdown()
}
The above script will println all Tag entities currently in the cache
7: When starting up the Docker instance, make sure you've exposed the port, without the -p option, nothing will work.
docker run --name=hazelcast -d=true -p 5701:5701 -e JAVA_OPTS="-Dhazelcast.local.publicAddress=127.0.0.1:5701" hazelcast/hazelcast:3.10.4
8: Check the Hazelcast logs to see if your Java / Kotlin client is connecting:
docker logs -f hazelcast
You should see something like this when there's a connection:
Sep 13, 2018 9:05:06 PM com.hazelcast.client.ClientEndpointManager
INFO: [127.0.0.1]:5701 [dev] [3.10.4] Destroying ClientEndpoint{connection=Connection[id=32, /172.17.0.2:5701->/172.17.0.1:56574, endpoint=[172.17.0.1]:56574, alive=false, type=JAVA_CLIENT], principal='ClientPrincipal{uuid='99cbf1b4-d11c-462d-bd87-4c069bc9b2ef', ownerUuid='2fb66fa1-a17f-49fe-ba2b-bf585d43906d'}, ownerConnection=true, authenticated=true, clientVersion=3.10.4, creationTime=1536872631771, latest statistics=null}
Sep 13, 2018 9:05:19 PM com.hazelcast.nio.tcp.TcpIpAcceptor
INFO: [127.0.0.1]:5701 [dev] [3.10.4] Accepting socket connection from /172.17.0.1:56576
Sep 13, 2018 9:05:19 PM com.hazelcast.nio.tcp.TcpIpConnectionManager
INFO: [127.0.0.1]:5701 [dev] [3.10.4] Established socket connection between /172.17.0.2:5701 and /172.17.0.1:56576
Sep 13, 2018 9:05:19 PM com.hazelcast.client.impl.protocol.task.AuthenticationMessageTask
INFO: [127.0.0.1]:5701 [dev] [3.10.4] Received auth from Connection[id=33, /172.17.0.2:5701->/172.17.0.1:56576, endpoint=null, alive=true, type=JAVA_CLIENT], successfully authenticated, principal: ClientPrincipal{uuid='ff51de39-fd9c-4ecf-bdd4-bbdb6ec6c79e', ownerUuid='2fb66fa1-a17f-49fe-ba2b-bf585d43906d'}, owner connection: true, client version: 3.10.4
These seems to be the crux of getting hazelcast hibernate working.

Hibernate fails to create table in MySQL

Hibernate fails to create new table new table for Entity in MySQL eventhough property "hibernate.hbm2ddl.auto" is set to "create-drop". It also fails with "create" and "update" with the same error: org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement.
Note: Database "test" is already created and empty.
If a table named "Test" is already created (even if its empty) everything runs perfectly and table is updated.
But after hours of Stackoverflowing and Googling I am giving up. I will create empty tables previously. If someone could find a better solution would be great.
Thanks,
Runing on Ubuntu 16.04.1 64 bits with Oracle Java 1.8.0_101. MySQL Server is 5.7.15. IDE used Eclipse Neon.
Code follows:
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>HibernateTest</groupId>
<artifactId>HibernateTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.4.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.4</version>
</dependency>
</dependencies>
</project>
hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.show_sql">true</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<mapping class="Test"></mapping>
</session-factory>
</hibernate-configuration>
Main.java:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class Main {
public static void main(String[] args) {
System.out.println("Iniciando HibernateTest.");
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
try {
SessionFactory sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Test test = new Test();
test.setId(1);
session.save(test);
session.getTransaction().commit();
session.close();
System.out.println("Test Ok.");
}
catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
// so destroy it manually.
e.printStackTrace();
System.out.println("KO - " + e.getMessage());
StandardServiceRegistryBuilder.destroy( registry );
}
}
}
Test.java:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
public class Test {
#Id
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
Complete output:
Iniciando HibernateTest.
oct 30, 2016 2:52:44 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.4.Final}
oct 30, 2016 2:52:44 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
oct 30, 2016 2:52:44 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
oct 30, 2016 2:52:44 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
oct 30, 2016 2:52:45 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
oct 30, 2016 2:52:45 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/test]
oct 30, 2016 2:52:45 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
oct 30, 2016 2:52:45 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
oct 30, 2016 2:52:45 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Sun Oct 30 02:52:45 CEST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
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:267)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:231)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
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:240)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
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.boot.MetadataSources.buildMetadata(MetadataSources.java:179)
at Main.main(Main.java:17)
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:123)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:42)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:20)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections$Builder.build(PooledConnections.java:161)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:109)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:72)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
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:257)
... 13 more
Caused by: java.sql.SQLException: The server time zone value 'CEST' 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:569)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:537)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:527)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:512)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:480)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:498)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:494)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:69)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1634)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:637)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:351)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:224)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 28 more
Caused by: com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: The server time zone value 'CEST' 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:293)
at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:2424)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1767)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1624)
... 32 more
KO - Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
oct 30, 2016 2:52:45 AM org.hibernate.service.internal.AbstractServiceRegistryImpl stopService
INFO: HHH000369: Error stopping service [class org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] : java.lang.NullPointerException
Changing hibernate.dialect from MySQLInnoDBDialect in hibernate.cfg.xml to did MySQLDialect the trick (wonder why)
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

Maven 3.2.1 + Hibernate 4.3.4 - Unable to build entity manager factory - Caused by: ParameterizedTypeImpl cannot be cast to java.lang.Class

I have migrated a Hibernate 4.3.4 to a Maven 3.2.1 project. I have created just one jar file with maven-shade-plugin, but when I start it I have the following exception:
Mar 17, 2014 10:44:35 AM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Mar 17, 2014 10:44:35 AM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Mar 17, 2014 10:44:35 AM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Mar 17, 2014 10:44:35 AM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: MfsDao
...]
Mar 17, 2014 10:44:36 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.4.Final}
Mar 17, 2014 10:44:36 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=org.h2.Driver, hibernate.service.allow_crawling=false, hibernate.dialect=org.hibernate.dialect.H2Dialect, hibernate.max_fetch_depth=5, hibernate.format_sql=true, hibernate.generate_statistics=true, hibernate.connection.username=sa, hibernate.connection.url=jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE, hibernate.bytecode.use_reflection_optimizer=false, hibernate.jdbc.batch_versioned_data=true, hibernate.connection.pool_size=5}
Mar 17, 2014 10:44:36 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Mar 17, 2014 10:44:44 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
javax.persistence.PersistenceException: Unable to build entity manager factory
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:81)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at de.cegelec.vwezlt.mfs.dao.MfsEntityManager.getEntityManagerFactory(MfsEntityManager.java:117)
at de.cegelec.vwezlt.mfs.dao.MfsEntityManager.getMfsEntityManager(MfsEntityManager.java:25)
at de.cegelec.vwezlt.mfsvert.main.MfsVert.main(MfsVert.java:168)
Caused by: java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl cannot be cast to java.lang.Class
at org.hibernate.cfg.AttributeConverterDefinition.<init>(AttributeConverterDefinition.java:67)
at org.hibernate.cfg.Configuration.addAttributeConverter(Configuration.java:2690)
at org.hibernate.cfg.Configuration.addAttributeConverter(Configuration.java:2641)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.buildHibernateConfiguration(EntityManagerFactoryBuilderImpl.java:1129)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:846)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:397)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:73)
I have debugged and I have found that the class which raises the exception is org.apache.logging.log4j.core.appender.db.jpa.converter.ContextMapAttributeConverter.
In my pom I have a dependency with log4j 2.0-rc1 as dependency:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-rc1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-rc1</version>
</dependency>
It has worked fine before I tried to integrate all in Maven.
Any idea?
Thanks in advance!
As mentioned by aaronfc already, there is an open ticket on hibernate JIRA: https://hibernate.atlassian.net/browse/HHH-8804
So the Problem is an collision with Log4j2 converters, more detailed, the db appender JPA converters.
However, the problems occurs with the "fat" jar only...
Workaround: If you use maven-shade-plugin to pack your jar - and don't need any log4j2 db appender, you could exclude the colliding Converter classes:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<shadedClassifierName>jar-with-dependencies</shadedClassifierName>
<filters>
<filter>
<artifact>org.apache.logging.log4j:*</artifact>
<excludes>
<exclude>org/apache/logging/log4j/core/appender/db/jpa/converter/*</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
I stumbled upon this also. There is an open ticket on https://hibernate.atlassian.net/browse/HHH-8804
I "workarounded" it by downgrading to Hibernate 4.2.12.Final and JPA2.0. Hope it helps!
Edit:
Sorry, didn't see that this was a two months old post, anyway hope it is useful for somebody :P
In extension to #hartmut's answer, if you're using Gradle, include Gradle Shadow, and do the following in build.gradle:
shadowJar {
exclude 'org/apache/logging/log4j/core/appender/db/jpa/converter/*'
}
You can then run gradle shadowJar to create the jar
I have found a workaround that works. Instead to create a "fat" jar, I have created a Jar with my project and all the dependencies in a separate "lib" folder (included Hibernate of course).
I don't know way, but it works now.

Categories