Azure Sql Server and Hibernate Java Mac - java

I have Eclipse and Hibernate that connect to Azure Sql Server (Microsoft Azure for Students). I uploaded to a git the project that works perfectly on the school pc with Windows but here on my Mac can not connect to server ... The only difference is the Hibernate Library & JDBC library, the code it's the same. :(
output:
Jan 11, 2017 4:03:51 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.3.Final}
Jan 11, 2017 4:03:51 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 11, 2017 4:03:51 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jan 11, 2017 4:03:52 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.
Jan 11, 2017 4:03:52 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jan 11, 2017 4:03:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jan 11, 2017 4:03:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at URL [jdbc:sqlserver://usedproy.database.windows.net:1433;database=used;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;]
Jan 11, 2017 4:03:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=usuario#usedproy, password=****}
Jan 11, 2017 4:03:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jan 11, 2017 4:03:52 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Failed to create sessionFactory object.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
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:692)
at probandohibernate.PersonFactory.<clinit>(PersonFactory.java:31)
at probandohibernate.ProbandoHibernate.insert(ProbandoHibernate.java:55)
at probandohibernate.ProbandoHibernate.main(ProbandoHibernate.java:23)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:101)
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)
... 15 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: SQL Server did not return a response. The connection has been closed. ClientConnectionId:c2231f63-42b7-473b-8cab-e16e8473cb31
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1667)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1654)
at com.microsoft.sqlserver.jdbc.TDSReader.readPacket(IOBuffer.java:4844)
at com.microsoft.sqlserver.jdbc.TDSCommand.startResponse(IOBuffer.java:6154)
at com.microsoft.sqlserver.jdbc.TDSCommand.startResponse(IOBuffer.java:6106)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2907)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2234)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2220)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1326)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 30 more
Exception in thread "main" java.lang.NullPointerException
at probandohibernate.ProbandoHibernate.insert(ProbandoHibernate.java:82)
at probandohibernate.ProbandoHibernate.main(ProbandoHibernate.java:23)
Hibernate conf:
<?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 name="Hibernate">
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</property>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://***.database.windows.net:1433;database=****;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;</property>
<property name="hibernate.connection.username">***#***</property>
<property name="hibernate.connection.password">***</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="probandohibernate.modelo.Empleados"/>
</session-factory>
</hibernate-configuration>
Java Class:
package probandohibernate.modelo;
/**
*
* #author leo
*/
import java.sql.Date;
import javax.persistence.*;
/**
*
* #author John
*/
#Entity
#Table(name = "Empleados")
public class Empleados {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY) //Editado
private Long id;
#Column(name = "Nombre")
private String nombre;
#Column(name = "Apellidos")
private String apellido;
#Column(name = "FechaNacimiento")
private Date fechaNacimiento;
#Column(name = "Movil")
private String movil;
public Empleados() {
}
public Empleados(String nombre, String apellido, Date fechaNacimiento, String movil) {
this.nombre = nombre;
this.apellido = apellido;
this.fechaNacimiento = fechaNacimiento;
this.movil = movil;
}
public Long getId() {
return id;
}
public String getNombre() {
return nombre;
}
public String getApellido() {
return apellido;
}
public Date getFechaNacimiento() {
return fechaNacimiento;
}
public String getMovil() {
return movil;
}
public void setId(Long id) {
this.id = id;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public void setFechaNacimiento(Date fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public void setMovil(String movil) {
this.movil = movil;
}
#Override
public String toString() {
return "Empleado [id=" + id + ", nombre=" + nombre + ", apellido=" + apellido + ", fechaNacimiento="
+ fechaNacimiento + ", movil=" + movil + "]";
}
}
Hibernate Class:
package probandohibernate;
/**
*
* #author leo
*/
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import probandohibernate.modelo.Empleados;
public class PersonFactory {
private static ServiceRegistry serviceRegistry;
private static final SessionFactory sessionFactory;
static {
try {
Configuration configuration=new Configuration()
.configure(); // configures settings from hibernate.cfg.xml
configuration.addAnnotatedClass(Empleados.class);
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
// If you miss the below line then it will complaing about a missing dialect setting
serviceRegistryBuilder.applySettings(configuration.getProperties());
serviceRegistry = serviceRegistryBuilder.build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
private static void read(){
Session session = null;
try {
try {
sessionFactory = PersonFactory.getSessionFactory();
session = sessionFactory.openSession();
#SuppressWarnings("unchecked")
List<Empleados> list = session.createQuery("from Empleados")
.list();
for (Empleados p : list)
System.out.println(p);
} catch (Exception e) {
e.printStackTrace();
}
} finally {
session.close();
}
}
Libraries:
Update:
I just disabled the firewall of Sierra and of Avast and a get this Exception.
Jan 13, 2017 12:40:54 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
Jan 13, 2017 12:40:54 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 13, 2017 12:40:54 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jan 13, 2017 12:40:54 AM 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.
Jan 13, 2017 12:40:54 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jan 13, 2017 12:40:54 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jan 13, 2017 12:40:54 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at URL [jdbc:sqlserver://usedproy.database.windows.net:1433;database=used;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;]
Jan 13, 2017 12:40:54 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=usuario#usedproy, password=****}
Jan 13, 2017 12:40:54 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jan 13, 2017 12:40:54 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Failed to create sessionFactory object.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
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:244)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
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:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
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:692)
at probandohibernate.PersonFactory.<clinit>(PersonFactory.java:34)
at probandohibernate.ProbandoHibernate.insert(ProbandoHibernate.java:65)
at probandohibernate.ProbandoHibernate.main(ProbandoHibernate.java:30)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:101)
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:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
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:234)
... 15 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Connection reset ClientConnectionId:93c921a0-b8bf-48fe-b3da-0064cc309d63
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1667)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1654)
at com.microsoft.sqlserver.jdbc.TDSChannel.read(IOBuffer.java:1789)
at com.microsoft.sqlserver.jdbc.TDSReader.readPacket(IOBuffer.java:4838)
at com.microsoft.sqlserver.jdbc.TDSCommand.startResponse(IOBuffer.java:6154)
at com.microsoft.sqlserver.jdbc.TDSCommand.startResponse(IOBuffer.java:6106)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2907)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2234)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2220)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1326)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 30 more
Exception in thread "main" java.lang.NullPointerException
at probandohibernate.ProbandoHibernate.insert(ProbandoHibernate.java:92)
at probandohibernate.ProbandoHibernate.main(ProbandoHibernate.java:30)
- More info:
If help something with JDBC doesn't work too
Code of JDBC:
package es.iesnervion.model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MakingStatement {
public static void main(String[] args) {
// Carga el driver
try {
// Carga la clase del driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Define the data source for the driver
String sourceURL = "jdbc:sqlserver://******.database.windows.net:1433;database=***;user=***#usedproy;password=****;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
String miSelect = "SELECT ID, Nombre FROM Empleados";
// Crear una connexi�n con el DriverManager
Connection connexionBaseDatos =
DriverManager.getConnection(sourceURL);
Statement sentencia = connexionBaseDatos.createStatement();
ResultSet nombresProductos = sentencia.executeQuery(miSelect);
// Mostrar los datos del ResultSet
System.out.println("Productos -> PVP");
System.out.println("------------------------------------------");
while (nombresProductos.next())
System.out.println(nombresProductos.getString("Nombre")+ " -> " +
nombresProductos.getInt("ID"));
// Cerrar conexi�n
connexionBaseDatos.close();
}
catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
}
catch (SQLException sqle) {
sqle.printStackTrace();
}
}
}

According to your comments, the issue seems to be the same as the SO thread SQL Server JDBC Error on Java 8: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption, please follow the answer for the existing SO thread & the reference for properties configuration of connection string to try to solve it. Any update, please feel free to let me know.

Related

I can't extract data from the table and make a connection with the hibernate orm

I start the server, I can't fill out the list in any way, the database is connected and working, table work, I can't extract data from the table and make a connection with the hibernate orm
And if I try to add writes:
Caused by: org.hibernate.MappingException: Unknown entity: ru.todolist.javafx.objects.Task
class TaskHibernateImpl
public class TaskHibernateImpl implements TaskDao {
....
public ObservableList<Task> tasks = FXCollections.observableArrayList();
#SuppressWarnings("unchecked")
#Override
public ObservableList<Task> findAll() {
System.out.println("tasks.isEmpty() = " + tasks.isEmpty());
tasks.clear();
Session session = getSessionFactory().openSession();
tasks.addAll(session.createCriteria(Task.class).list()); //here it is not filled in
System.out.println("tasks.isEmpty() = " + tasks.isEmpty()); // true list empty
session.close();
return tasks;
}
...
}
class Task object model
[![enter image description here][1]][1]
File hibernate.cfg.xml hibernate configuration 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="connection.url">jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db-->
<property name="connection.url">jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db</property>
<property name="connection.driver_class">org.sqlite.JDBC</property>
<property name="hibernate.show_sql">true</property>
<property name="dialect">ru.todolist.javafx.hibernate.dialect.SQLiteDialect</property>
<property name="hibernate.connection.autocommit">true</property>
<mapping class="ru.todolist.javafx.hibernate.TodoEntity"/>
<mapping resource="TodoEntity.hbm.xml"/>
<!-- <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>
TodoEntity.hbm.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="ru.todolist.javafx.hibernate.TodoEntity" table="todo" schema="main">
<id name="id">
<column name="id" sql-type="integer"/>
</id>
<property name="task">
<column name="task" sql-type="text"/>
</property>
<property name="taskCreateTime">
<column name="task_create_time" sql-type="text"/>
</property>
<property name="status">
<column name="status" sql-type="text" not-null="true"/>
</property>
</class>
</hibernate-mapping>
table todo work
the todolistFx program itself,see empty
program structure
logs run
D:\jdk11\bin\java.exe --module-path D:\openjFX18\lib --add-modules=javafx.controls,javafx.fxml "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2022.2.2\lib\idea_rt.jar=51993:C:\Program Files\JetBrains\IntelliJ IDEA 2022.2.2\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\target\classes;D:\openjFX18\lib\javafx-swt.jar;D:\openjFX18\lib\javafx.web.jar;D:\openjFX18\lib\javafx.base.jar;D:\openjFX18\lib\javafx.fxml.jar;D:\openjFX18\lib\javafx.media.jar;D:\openjFX18\lib\javafx.swing.jar;D:\openjFX18\lib\javafx.controls.jar;D:\openjFX18\lib\javafx.graphics.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\classmate-1.5.1.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\hibernate-commons-annotations-5.1.0.Final.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\dom4j-2.1.1.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\FastInfoset-1.2.15.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\antlr-2.7.7.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\istack-commons-runtime-3.0.7.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\jandex-2.1.1.Final.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\javax.activation-api-1.2.0.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\byte-buddy-1.10.7.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\javassist-3.24.0-GA.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\javax.persistence-api-2.2.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\jaxb-api-2.3.1.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\jboss-logging-3.3.2.Final.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\jboss-transaction-api_1.2_spec-1.1.1.Final.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\jaxb-runtime-2.3.1.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\stax-ex-1.8.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\txw2-2.3.1.jar;C:\Users\den\IdeaProjects\TodoListFx\TodoListFx\lib\hibernate-core-5.4.11.Final.jar;C:\Users\den\.m2\repository\org\hibernate\hibernate-core\5.4.11.Final\hibernate-core-5.4.11.Final.jar;C:\Users\den\.m2\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;C:\Users\den\.m2\repository\javax\persistence\javax.persistence-api\2.2\javax.persistence-api-2.2.jar;C:\Users\den\.m2\repository\org\javassist\javassist\3.24.0-GA\javassist-3.24.0-GA.jar;C:\Users\den\.m2\repository\net\bytebuddy\byte-buddy\1.10.7\byte-buddy-1.10.7.jar;C:\Users\den\.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Users\den\.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\den\.m2\repository\org\jboss\jandex\2.1.1.Final\jandex-2.1.1.Final.jar;C:\Users\den\.m2\repository\com\fasterxml\classmate\1.5.1\classmate-1.5.1.jar;C:\Users\den\.m2\repository\javax\activation\javax.activation-api\1.2.0\javax.activation-api-1.2.0.jar;C:\Users\den\.m2\repository\org\dom4j\dom4j\2.1.1\dom4j-2.1.1.jar;C:\Users\den\.m2\repository\org\hibernate\common\hibernate-commons-annotations\5.1.0.Final\hibernate-commons-annotations-5.1.0.Final.jar;C:\Users\den\.m2\repository\javax\xml\bind\jaxb-api\2.3.1\jaxb-api-2.3.1.jar;C:\Users\den\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.1\jaxb-runtime-2.3.1.jar;C:\Users\den\.m2\repository\org\glassfish\jaxb\txw2\2.3.1\txw2-2.3.1.jar;C:\Users\den\.m2\repository\com\sun\istack\istack-commons-runtime\3.0.7\istack-commons-runtime-3.0.7.jar;C:\Users\den\.m2\repository\org\jvnet\staxex\stax-ex\1.8\stax-ex-1.8.jar;C:\Users\den\.m2\repository\com\sun\xml\fastinfoset\FastInfoset\1.2.15\FastInfoset-1.2.15.jar;C:\Users\den\.m2\repository\org\xerial\sqlite-jdbc\3.39.3.0\sqlite-jdbc-3.39.3.0.jar;C:\Users\den\.m2\repository\org\openjfx\javafx-controls\17.0.2\javafx-controls-17.0.2.jar;C:\Users\den\.m2\repository\org\openjfx\javafx-controls\17.0.2\javafx-controls-17.0.2-win.jar;C:\Users\den\.m2\repository\org\openjfx\javafx-graphics\17.0.2\javafx-graphics-17.0.2.jar;C:\Users\den\.m2\repository\org\openjfx\javafx-graphics\17.0.2\javafx-graphics-17.0.2-win.jar;C:\Users\den\.m2\repository\org\openjfx\javafx-base\17.0.2\javafx-base-17.0.2.jar;C:\Users\den\.m2\repository\org\openjfx\javafx-base\17.0.2\javafx-base-17.0.2-win.jar;C:\Users\den\.m2\repository\org\openjfx\javafx-fxml\17.0.2\javafx-fxml-17.0.2.jar;C:\Users\den\.m2\repository\org\openjfx\javafx-fxml\17.0.2\javafx-fxml-17.0.2-win.jar;C:\Users\den\.m2\repository\org\controlsfx\controlsfx\11.1.1\controlsfx-11.1.1.jar;C:\Users\den\.m2\repository\org\kordamp\ikonli\ikonli-javafx\12.3.1\ikonli-javafx-12.3.1.jar;C:\Users\den\.m2\repository\org\kordamp\ikonli\ikonli-core\12.3.1\ikonli-core-12.3.1.jar ru.todolist.javafx.start.Main
сент. 30, 2022 7:17:30 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.11.Final}
сент. 30, 2022 7:17:31 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
сент. 30, 2022 7:17:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
сент. 30, 2022 7:17:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.sqlite.JDBC] at URL [jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db]
сент. 30, 2022 7:17:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {autocommit=true}
сент. 30, 2022 7:17:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: true
сент. 30, 2022 7:17:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
сент. 30, 2022 7:17:31 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: ru.todolist.javafx.hibernate.dialect.SQLiteDialect
сент. 30, 2022 7:17:32 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
сент. 30, 2022 7:17:32 PM org.hibernate.internal.SessionImpl createCriteria
WARN: HHH90000022: Hibernate's legacy org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead
сент. 30, 2022 7:17:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
сент. 30, 2022 7:17:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.sqlite.JDBC] at URL [jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db]
сент. 30, 2022 7:17:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {autocommit=true}
сент. 30, 2022 7:17:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: true
сент. 30, 2022 7:17:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
сент. 30, 2022 7:17:32 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: ru.todolist.javafx.hibernate.dialect.SQLiteDialect
сент. 30, 2022 7:17:32 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
сент. 30, 2022 7:17:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
сент. 30, 2022 7:17:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.sqlite.JDBC] at URL [jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db]
сент. 30, 2022 7:17:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {autocommit=true}
сент. 30, 2022 7:17:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: true
сент. 30, 2022 7:17:32 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
сент. 30, 2022 7:17:32 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: ru.todolist.javafx.hibernate.dialect.SQLiteDialect
сент. 30, 2022 7:17:32 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
сент. 30, 2022 7:17:32 PM org.hibernate.internal.SessionImpl createCriteria
WARN: HHH90000022: Hibernate's legacy org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead
I fill in my ObservableList , list , which I got from the table
as you can see the todolist program has filled up
class TaskHibernateImpl in this class, data is taken from the table ,method tasksclear() checking the table clearing so that there is no double table filling, we clear the current one.createQuery("From Task") here I attention! specify my class entity
public class TaskHibernateImpl implements TaskDao {
...
public ObservableList<Task> findAll() {
tasks.clear(); //
tasks.addAll(HibernateSessionFactoryUtil.getSessionFactory().openSession().createQuery("From Task").list());
System.out.println("tasks.isEmpty() = " + tasks.isEmpty()); // false
return tasks;
}
...
}
class HibernateSessionFactoryUtil -> In this class, I create a configuration and add a class to it, with a JPA configuration
public class HibernateSessionFactoryUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public HibernateSessionFactoryUtil() {
}
public static SessionFactory getSessionFactory(){
if(sessionFactory == null){
try{
Configuration configuration = new Configuration().configure();
// here necessary class add
configuration.addAnnotatedClass(ru.todolist.javafx.objects.Task.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
} catch (Exception e) {
System.out.println("Exception !" + e);
}
}
return sessionFactory;
}
}
class Task -> In this class I put JPA annotations #Entity, #Id, #Column
package ru.todolist.javafx.objects;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javax.persistence.*;
import java.util.Date;
#Entity
#Table(name = "todo", schema = "main", catalog = "")
public class Task {
private SimpleIntegerProperty id = new SimpleIntegerProperty();
private SimpleStringProperty task = new SimpleStringProperty("");
private static Date date = new Date();
private SimpleStringProperty time = new SimpleStringProperty(date.toString());
// private static boolean statusBegin = false;
private static String statusText = "не выполнена";
private SimpleStringProperty status = new SimpleStringProperty(statusText);
public Task() {
}
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "id", nullable = false)
public int getId() {
return id.get();
}
public SimpleIntegerProperty idProperty() {
return id;
}
public void setId(int id) {
this.id.set(id);
}
#Basic
#Column(name = "task", nullable = false, length = -1)
public String getTask() {
return task.get();
}
public SimpleStringProperty taskProperty() {
return task;
}
public void setTask(String task) {
this.task.set(task);
}
#Basic
#Column(name = "task_create_time", nullable = false, length = -1)
public String getTime() {
return time.get();
}
public SimpleStringProperty timeProperty() {
return time;
}
public void setTime(String time) {
this.time.set(time);
}
#Basic
#Column(name = "status", nullable = true, length = -1)
public String getStatus() {
return status.get();
}
public SimpleStringProperty statusProperty() {
return status;
}
public void setStatus(String status) {
this.status.set(status);
}
#Override
public String toString() {
return "Task{" +
"id=" + id +
", task=" + task +
", time=" + time +
", status=" + status +
'}';
}
}
class hibernate.cfg.xml hibernate configuration class
<?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="connection.url">jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db</property>
<property name="connection.driver_class">org.sqlite.JDBC</property>
<property name="hibernate.show_sql">true</property>
<property name="dialect">ru.todolist.javafx.hibernate.dialect.SQLiteDialect</property>
<property name="hibernate.connection.autocommit">true</property>
<mapping class="ru.todolist.javafx.objects.Task"/>
<!-- <mapping resource="Task.hbm.xml"/>-->
<!-- <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>

It is necessary to fill the ObservableList by taking data from the table using hibernate

It is necessary to fill the ObservableList by taking data from the table using hibernate, it turns out to be empty, the table is working, it turns out to be empty, the table works,
session open
class Main
public class Main {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public static void main(String[] args) {
findAll();
}
#SuppressWarnings({"unchecked", "deprecation"})
public static ObservableList<Task> findAll() {
ObservableList<Task> observableTasks = FXCollections.observableArrayList();
Session session = getSessionFactory().openSession();
observableTasks.addAll(session.createCriteria(Task.class).list());
System.out.println("observableTasks = " + observableTasks.isEmpty()); // true empty
session.close();
return observableTasks;
}
public static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
}
file hibernate.cfg.xml hibernate configuration class
<?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="connection.url">jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db-->
<property name="connection.url">jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db</property>
<property name="connection.driver_class">org.sqlite.JDBC</property>
<property name="hibernate.show_sql">true</property>
<property name="dialect">org.example.hibernate.dialect.SQLiteDialect</property>
<property name="hibernate.connection.autocommit">true</property>
<mapping class="org.example.test_hibernate_connect_bd.Task"/>
<mapping resource="TodoTask.hbm.xml"/>
<!-- <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>
file TodoTask.hbm.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.example.test_hibernate_connect_bd.Task" table="todo" schema="main">
<id name="id">
<column name="id" sql-type="integer"/>
</id>
<property name="task">
<column name="task" sql-type="text"/>
</property>
<property name="time">
<column name="task_create_time" sql-type="text"/>
</property>
<property name="status">
<column name="status" sql-type="text" not-null="true"/>
</property>
</class>
</hibernate-mapping>
class Task the object itself
logs current launch
сент. 30, 2022 8:40:14 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.11.Final}
сент. 30, 2022 8:40:15 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.sqlite.JDBC] at URL [jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db]
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {autocommit=true}
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: true
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
сент. 30, 2022 8:40:15 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.example.hibernate.dialect.SQLiteDialect
сент. 30, 2022 8:40:16 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
сент. 30, 2022 8:40:16 PM org.hibernate.internal.SessionImpl createCriteria
WARN: HHH90000022: Hibernate's legacy org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead
observableTasks = true
project structure
I fill in the list first, because the ObservableList class inherits from extends List , then it gets the same addAll(....) methods. I fill in my ObservableList , list , which I got from the table.
class Main
package org.example;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.example.objects.Task;
import org.example.utils.HibernateSessionFactoryUtil;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static ObservableList<Task> personList = FXCollections.observableArrayList();
public static List<Task> ist = new ArrayList<>();
public static void main(String[] args) {
findAll();
}
#SuppressWarnings({"unchecked", "deprecation"})
public static ObservableList<Task> findAll() {
ist = HibernateSessionFactoryUtil.getSessionFactory().openSession().createQuery("From Task").list();
personList.addAll(ist);
System.out.println("personList.isEmpty() = " + personList.isEmpty());
return personList;
}
}
class HibernateSessionFactoryUtil -> In this class, I create a configuration and add a class to it, with a JPA configuration
package org.example.utils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateSessionFactoryUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public HibernateSessionFactoryUtil() {
}
public static SessionFactory getSessionFactory(){
if(sessionFactory == null){
try{
Configuration configuration = new Configuration().configure();
// here necessary class add
configuration.addAnnotatedClass(org.example.objects.Task.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
} catch (Exception e) {
System.out.println("Exception !" + e);
}
}
return sessionFactory;
}
}
class Task In this class I put JPA annotations #Entity, #Id, #Column
package org.example.objects;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javax.persistence.*;
#Entity
#Table(name = "todo", schema = "main", catalog = "")
public class Task {
private SimpleIntegerProperty id = new SimpleIntegerProperty();
private SimpleStringProperty task = new SimpleStringProperty("");
private SimpleStringProperty time = new SimpleStringProperty("");
private SimpleStringProperty status = new SimpleStringProperty("");
public Task() {
}
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "id", nullable = false)
public int getId() {
return id.get();
}
public SimpleIntegerProperty idProperty() {
return id;
}
public void setId(int id) {
this.id.set(id);
}
#Basic
#Column(name = "task", nullable = false, length = -1)
public String getTask() {
return task.get();
}
public SimpleStringProperty taskProperty() {
return task;
}
public void setTask(String task) {
this.task.set(task);
}
#Basic
#Column(name = "task_create_time", nullable = false, length = -1)
public String getTime() {
return time.get();
}
public SimpleStringProperty timeProperty() {
return time;
}
public void setTime(String time) {
this.time.set(time);
}
#Basic
#Column(name = "status", nullable = true, length = -1)
public String getStatus() {
return status.get();
}
public SimpleStringProperty statusProperty() {
return status;
}
public void setStatus(String status) {
this.status.set(status);
}
#Override
public String toString() {
return "Task{" +
"id=" + id +
", task=" + task +
", time=" + time +
", status=" + status +
'}';
}
}
the result I wanted to see is that the list is not empty
окт. 01, 2022 8:33:53 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.11.Final}
окт. 01, 2022 8:33:54 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.sqlite.JDBC] at URL [jdbc:sqlite:C:/Users/den/IdeaProjects/TestHibernate/db/todolist.db]
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {autocommit=true}
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: true
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
окт. 01, 2022 8:33:55 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.example.hibernate.dialect.SQLiteDialect
окт. 01, 2022 8:33:55 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
****Hibernate:
select task0_.id as id1_0_, task0_.status as status2_0_, task0_.task as task3_0_, task0_.task_create_time as task_cre4_0_ from todo task0_
personList.isEmpty() = false**** <----- here result

Java Hibernate exception

For some reason it does not find Polica even tho i have mapped it in code, created seperate file to map it etc. What is the problem?
In file PolicaDAO2 i am also getting createQuery deprecated for some reason if anyone knows solution to this aswell let me know. I tried multiple things aswell as you can see in the file under findall() function
Exception:
Aug 09, 2022 12:41:34 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 6.1.2.Final
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using built-in connection pool (not intended for production use)
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: Loaded JDBC driver class: com.mysql.cj.jdbc.Driver
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001012: Connecting with JDBC URL [jdbc:mysql://127.0.0.1:3306/Wallboard]
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=root}
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH10001115: Connection pool size: 20 (min=1)
Aug 09, 2022 12:41:43 PM org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl logSelectedDialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 09, 2022 12:41:47 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using built-in connection pool (not intended for production use)
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: Loaded JDBC driver class: com.mysql.cj.jdbc.Driver
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001012: Connecting with JDBC URL [jdbc:mysql://127.0.0.1:3306/Wallboard]
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=root}
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH10001115: Connection pool size: 20 (min=1)
Aug 09, 2022 12:41:48 PM org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl logSelectedDialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 09, 2022 12:41:48 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Exception in thread "main" java.lang.IllegalArgumentException: org.hibernate.query.sqm.UnknownEntityException: Could not resolve root entity 'Polica'
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:175)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:182)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:761)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:663)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:127)
at digiwallboard.DAO.PolicaDAO2.findAll(PolicaDAO2.java:81)
at digiwallboard.Service.PolicaService.findAll(PolicaService.java:18)
at Main.main(Main.java:27)
Caused by: org.hibernate.query.sqm.UnknownEntityException: Could not resolve root entity 'Polica'
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitRootEntity(SemanticQueryBuilder.java:1628)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitRootEntity(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$RootEntityContext.accept(HqlParser.java:1874)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitEntityWithJoins(SemanticQueryBuilder.java:1548)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitFromClause(SemanticQueryBuilder.java:1539)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuery(SemanticQueryBuilder.java:833)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuerySpecExpression(SemanticQueryBuilder.java:629)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuerySpecExpression(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$QuerySpecExpressionContext.accept(HqlParser.java:1218)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSimpleQueryGroup(SemanticQueryBuilder.java:623)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSimpleQueryGroup(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$SimpleQueryGroupContext.accept(HqlParser.java:1131)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSelectStatement(SemanticQueryBuilder.java:399)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitStatement(SemanticQueryBuilder.java:358)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.buildSemanticModel(SemanticQueryBuilder.java:285)
at org.hibernate.query.hql.internal.StandardHqlTranslator.translate(StandardHqlTranslator.java:81)
at org.hibernate.internal.AbstractSharedSessionContract.lambda$createQuery$2(AbstractSharedSessionContract.java:748)
at org.hibernate.query.internal.QueryInterpretationCacheStandardImpl.createHqlInterpretation(QueryInterpretationCacheStandardImpl.java:141)
at org.hibernate.query.internal.QueryInterpretationCacheStandardImpl.resolveHqlInterpretation(QueryInterpretationCacheStandardImpl.java:128)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:745)
... 5 more
Main.java
import digiwallboard.Util.HibernateUtil;
import digiwallboard.Entity.*;
import java.util.List;
import digiwallboard.DAO.*;
import digiwallboard.Service.PolicaService;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
PolicaService policaService = new PolicaService();
List<Polica> pol = policaService.findAll();
for(Polica p : pol) {
System.out.println("-" + p.toString());
}
}
}
PolicaDAO2.java
package digiwallboard.DAO;
import java.util.List;
import javax.persistence.TypedQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import digiwallboard.Entity.Polica;
public class PolicaDAO2 implements PolicaDaoInterface<Polica, String> {
private Session currentSession;
private Transaction currentTransaction;
public PolicaDAO2() {
}
public Session openCurrentSession() {
currentSession = getSessionFactory().openSession();
return currentSession;
}
public Session openCurrentSessionwithTransaction() {
currentSession = getSessionFactory().openSession();
currentTransaction = currentSession.beginTransaction();
return currentSession;
}
public void closeCurrentSession() {
currentSession.close();
}
public void closeCurrentSessionwithTransaction() {
currentTransaction.commit();
currentSession.close();
}
private static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
configuration.addAnnotatedClass(Polica.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
return sessionFactory;
}
public Session getCurrentSession() {
return currentSession;
}
public void setCurrentSession(Session currentSession) {
this.currentSession = currentSession;
}
public Transaction getCurrentTransaction() {
return currentTransaction;
}
public void setCurrentTransaction(Transaction currentTransaction) {
this.currentTransaction = currentTransaction;
}
#SuppressWarnings("deprecation")
public void persist(Polica entity) {
getCurrentSession().save(entity);
}
#SuppressWarnings({ "unchecked", "deprecation" })
public List<Polica> findAll() {
Session session = openCurrentSession();
TypedQuery<Polica> result = (TypedQuery<Polica>) openCurrentSession().createQuery("FROM Polica");
List<Polica> result = query.getResultList();
closeCurrentSession();
/*
Query query = getCurrentSession().createQuery("select * from Polica");
List<Polica> pol = (List<Polica>) getCurrentSession().createNativeQuery("from Polica").list();
return pol;
*/
return result;
/*
TypedQuery<Polica> query = createQuery( "select * from Polica");
return query.getResultList();
*/
}
}
PolicaDaoInterface.java
package digiwallboard.DAO;
import java.io.Serializable;
import java.util.List;
public interface PolicaDaoInterface<T, Id extends Serializable> {
public List<T> findAll();
}
Polica.java
EDIT: IF YOU ARE USING HIBERNATE 6.0+ DO NOT USE JAVAX.PERSISTENCE LIKE I DID HERE THIS IS ONE OF THE REASONS I WAS GETTING THE EXCEPTION INSTEAD USE JAKARTA.PERSISTENCE
package digiwallboard.Entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "Polica")
public class Polica {
#Id
#Column(name="id")
private int id;
#Column(name="ime_pol")
private String ime_pol;
public Polica() {
}
public Polica(int id, String ime_pol) {
super();
this.id = id;
this.ime_pol = ime_pol;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIme_pol() {
return ime_pol;
}
public void setIme_pol(String ime_pol) {
this.ime_pol = ime_pol;
}
#Override
public String toString() {
return "Polica [id=" + id + ", ime_pol=" + ime_pol + "]";
}
}
PolicaService.java
package digiwallboard.Service;
import java.util.List;
import digiwallboard.DAO.PolicaDAO2;
import digiwallboard.Entity.Polica;
public class PolicaService {
private static PolicaDAO2 policaDao;
public PolicaService() {
policaDao = new PolicaDAO2();
}
public List<Polica> findAll() {
policaDao.openCurrentSession();
List<Polica> police = policaDao.findAll();
policaDao.closeCurrentSession();
return police;
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">Root123</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/Wallboard</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<!-- <mapping class="springfoxdemo.java.swagger.Polica" resource="springfoxdemo/java/swagger/Polica.hbm.xml"/> -->
<mapping class="digiwallboard.Entity.Polica"/>
</session-factory>
</hibernate-configuration>
hibernate.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="digiwallboard.Entity.Polica" table="Polica">
<id name="id" type="int" column="id">
<column name="id" />
</id>
<property name="ime_pol" column="ime_pol"
type="String">
</property>
</class>
</hibernate-mapping>
First of all, to avoid deprecation warnings, you should use the type safe variant of createQuery:
TypedQuery<Polica> result = openCurrentSession().createQuery("FROM Polica", Polica.class);
It's hard to say why your code is not working, but I have a few ideas what you could try. Note that you don't reference the hibernate.hbm.xml file anywhere and you commented out the reference to some other file Polica.hbm.xml, though the contents are unnecessary anyway as the annotations on the entity class are enough.
You are correctly listing the class through <mapping class="digiwallboard.Entity.Polica"/>, so it should be picked up by Hibernate. My guess is, that either some of your hbm.xml files that you might reference in your real app are interfering somehow, i.e. registering the entity type under a different name, or that your configuration is not picked up for some reason.
You can check which entities Hibernate found by inspecting getSessionFactory().getMetamodel().getEntities(), and if you find your entity there, check what EntityType#getName() reports, as that is the under which you can use the entity in HQL.

Inserting a new row in my table not working

Main
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import javax.persistence.EntityManager;
import model.Companie;
import repository.CompanieRepository;
import java.util.UUID;
public class Main
{
private static final SessionFactory sessionFactory;
private static final EntityManager entityManager;
static
{
Configuration configuration = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Companie.class);
sessionFactory = configuration.buildSessionFactory();
entityManager = sessionFactory.createEntityManager();
}
public static void main(String[] args)
{
CompanieRepository companieRepository = new CompanieRepository(entityManager);
Session session = sessionFactory.openSession();
Companie comp = new Companie(26, "some name", "some another thing", "that thing");
entityManager.persist(comp);
session.close();
System.out.println();
}
}
Company class
package model;
import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.UUID;
#Entity
#Data
public class Companie
{
// #Id
// #GeneratedValue(generator = "UUID")
// #GenericGenerator(name = "id", strategy = "org.hibernate.id.UUIDGenerator")
// #Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)")
// private UUID id;
#Id
private int id;
private String nume;
#Column(name = "cod_fiscal")
private String codFiscal;
#Column(name = "nr_registru_comertului")
private String nrRegistruComertului;
public Companie()
{
}
public Companie(int id, String nume, String codFiscal, String nrRegistruComertului)
{
this.id = id;
this.nume = nume;
this.codFiscal = codFiscal;
this.nrRegistruComertului = nrRegistruComertului;
}
}
Output
"C:\Program Files\Eclipse Adoptium\jdk-17.0.1.12-hotspot\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2021.2.3\lib\idea_rt.jar=49640:C:\Program Files\JetBrains\IntelliJ IDEA 2021.2.3\bin" -Dfile.encoding=UTF-8 -classpath D:\2xProjects\JavaPr\ContaApp\target\classes;C:\Users\Kentryx\.m2\repository\mysql\mysql-connector-java\8.0.25\mysql-connector-java-8.0.25.jar;C:\Users\Kentryx\.m2\repository\com\google\protobuf\protobuf-java\3.11.4\protobuf-java-3.11.4.jar;C:\Users\Kentryx\.m2\repository\org\hibernate\hibernate-core\5.6.1.Final\hibernate-core-5.6.1.Final.jar;C:\Users\Kentryx\.m2\repository\org\jboss\logging\jboss-logging\3.4.2.Final\jboss-logging-3.4.2.Final.jar;C:\Users\Kentryx\.m2\repository\javax\persistence\javax.persistence-api\2.2\javax.persistence-api-2.2.jar;C:\Users\Kentryx\.m2\repository\net\bytebuddy\byte-buddy\1.11.20\byte-buddy-1.11.20.jar;C:\Users\Kentryx\.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Users\Kentryx\.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\Kentryx\.m2\repository\org\jboss\jandex\2.2.3.Final\jandex-2.2.3.Final.jar;C:\Users\Kentryx\.m2\repository\com\fasterxml\classmate\1.5.1\classmate-1.5.1.jar;C:\Users\Kentryx\.m2\repository\javax\activation\javax.activation-api\1.2.0\javax.activation-api-1.2.0.jar;C:\Users\Kentryx\.m2\repository\org\hibernate\common\hibernate-commons-annotations\5.1.2.Final\hibernate-commons-annotations-5.1.2.Final.jar;C:\Users\Kentryx\.m2\repository\javax\xml\bind\jaxb-api\2.3.1\jaxb-api-2.3.1.jar;C:\Users\Kentryx\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.1\jaxb-runtime-2.3.1.jar;C:\Users\Kentryx\.m2\repository\org\glassfish\jaxb\txw2\2.3.1\txw2-2.3.1.jar;C:\Users\Kentryx\.m2\repository\com\sun\istack\istack-commons-runtime\3.0.7\istack-commons-runtime-3.0.7.jar;C:\Users\Kentryx\.m2\repository\org\jvnet\staxex\stax-ex\1.8\stax-ex-1.8.jar;C:\Users\Kentryx\.m2\repository\com\sun\xml\fastinfoset\FastInfoset\1.2.15\FastInfoset-1.2.15.jar;C:\Users\Kentryx\.m2\repository\org\projectlombok\lombok\1.18.22\lombok-1.18.22.jar Main
Jan 06, 2022 5:15:55 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.6.1.Final
Jan 06, 2022 5:15:55 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Jan 06, 2022 5:15:56 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jan 06, 2022 5:15:56 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/contabilitate]
Jan 06, 2022 5:15:56 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=clientDragos}
Jan 06, 2022 5:15:56 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jan 06, 2022 5:15:56 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jan 06, 2022 5:15:56 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
Jan 06, 2022 5:15:56 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#44784e2f] 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.
Jan 06, 2022 5:15:56 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Process finished with exit code 0
I have a problem that I can't solve at all. I'm new to hibernate. I want to insert a new row in my database. The table is created, if I run it for the first time everything goes just fine with the creation of the table and the columns. After that, when I try to insert a row my database is not updated. Java is not inserting anything.
PS: I tried to insert a new row in MySQL Workbench at it worked just fine, the problem is that in Java it won't do the trick.
PSS: I tried another solution: session.save(Object o) etc. Nothing worked
Because you forget to start the transaction to do your work. You have to commit the transaction to confirm saving your changes to DB.
If you are using the native Hibernate API , the codes should look likes:
Session session = sessionFactory.openSession();
session.getTransaction().begin();
session.persist(comp);
session.getTransaction().commit();
If you are using JPA API , the codes should like likes :
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
em.persist(comp);
em.getTransaction().commit();
perform the transaction in hibernateUtil class by invoking the session and then commit the transaction. The changes may affected to the db.

Hibernate 5 + Java 8 LocalDateTime

After a lot of reading and trying solutions from around the web, I've decided to ask for help because none of the solutions tried worked for me.
I have a very simple class which has a LocalDateTime variable.
I have created a MySQL table where I want to store the object containing this variable. For the LocalDateTime variable I've tried DateTime and TimeStamp types.
As far as I read, Hibernate 5 is supposed to support java.time.localdatetime. As I said, I've tried to use timestamp type and date, as long as timestamp and datetime as Mysql column types.
Always the same error.
This is a new project I am starting and I want to start using new Java 8 DateTime.
Here I attach all the classes and configuration files.
This is the Fecha.java, the object I want to map on my Mysql Table.
#Entity
#Table(name = "Fecha", catalog = "qtx590", uniqueConstraints = { #UniqueConstraint(columnNames = { "_id" }) })
public class Fecha implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "_id", nullable = false, unique = true)
private int _id;
#Column(name = "_idEmpresa", nullable = false)
private int _idEmpresa;
#Column(name = "_idTurno", nullable = false)
private int _idTurno;
#Column(name = "Momento", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
private LocalDateTime momento;
public Fecha() {
this._id = 99999;
this._idEmpresa = 99999;
this._idTurno = 99999;
this.momento = LocalDateTime.now();
}
public Fecha(int _id, int _idEmpresa, int idTurno, LocalDateTime momento) {
this._id = _id;
this._idEmpresa = _idEmpresa;
this._idTurno = idTurno;
this.momento = momento;
}
public String getMomentoString() {
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return this.momento.format(format);
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public int get_idEmpresa() {
return _idEmpresa;
}
public void set_idEmpresa(int _idEmpresa) {
this._idEmpresa = _idEmpresa;
}
public int get_idTurno() {
return _idTurno;
}
public void set_idTurno(int idTurno) {
this._idTurno = idTurno;
}
public LocalDateTime getmomento() {
return momento;
}
public void setmomento(LocalDateTime momento) {
this.momento = momento;
}
}
This is the HibernateConnectorClass
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateConnector {
private static HibernateConnector me;
private Configuration cfg;
private SessionFactory sessionFactory;
private HibernateConnector() throws HibernateException {
cfg = new Configuration();
sessionFactory = cfg.configure().buildSessionFactory();
}
public static synchronized HibernateConnector getInstance() throws HibernateException {
if (me == null) {
me = new HibernateConnector();
}
return me;
}
public Session getSession() throws HibernateException {
Session session = sessionFactory.openSession();
if (!session.isConnected()) {
this.reconnect();
}
return session;
}
private void reconnect() throws HibernateException {
this.sessionFactory = cfg.buildSessionFactory();
}
}
This is the test class to test it:
public class Prueba {
public static void main(String[] args) {
// TODO Auto-generated method stub
FechaDAO fechaDAO = new FechaDAO();
Fecha f = new Fecha();
System.out.println(f.getmomento());
fechaDAO.insertar(f);
System.out.println("FIN");
}
}
The hibernate.cfg.xml is working fine ( I know it because I tested it with other entity / table.
This is the specific for Fecha Object
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 31-ago-2015 12:58:20 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="Fecha" table="Fecha">
<id name="_id" type="java.lang.Integer" access="field">
<column name="_id" />
<generator class="increment" />
</id>
<property name="_idEmpresa" type="java.lang.Integer" access="field">
<column name="_idEmpresa" />
</property>
<property name="_idTurno" type="java.lang.Integer">
<column name="_idTurno" />
</property>
<property name="momento" type="java.time.LocalDateTime">
<column name="Momento" />
</property>
</class>
</hibernate-mapping>
And this the error:
2015-09-02T13:47:16.719
sep 02, 2015 1:47:16 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.0.Final}
sep 02, 2015 1:47:16 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
sep 02, 2015 1:47:16 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
sep 02, 2015 1:47:16 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.0.Final}
sep 02, 2015 1:47:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
sep 02, 2015 1:47:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://qtx590.li-bra.es:3306/qtx590]
sep 02, 2015 1:47:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=qtx590, password=****}
sep 02, 2015 1:47:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
sep 02, 2015 1:47:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
sep 02, 2015 1:47:17 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
sep 02, 2015 1:47:17 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Hibernate: select max(_id) from Fecha
Hibernate: insert into Fecha (_idEmpresa, _idTurno, Momento, _id) values (?, ?, ?, ?)
sep 02, 2015 1:47:18 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 22001
sep 02, 2015 1:47:18 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Data truncation: Incorrect datetime value: '’' for column 'Momento' at row 1
sep 02, 2015 1:47:18 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
sep 02, 2015 1:47:18 PM org.hibernate.internal.SessionImpl$5 mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [could not execute statement]
org.hibernate.exception.DataException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:52)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2823)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3323)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:447)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:333)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:335)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1224)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:464)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:2890)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2266)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:230)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)
at FechaDAO.insertar(FechaDAO.java:26)
at Prueba.main(Prueba.java:16)
Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '’' for column 'Momento' at row 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2983)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1604)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1519)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1504)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
... 19 more
Hibernate: insert into Fecha (_idEmpresa, _idTurno, Momento, _id) values (?, ?, ?, ?)
sep 02, 2015 1:47:18 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 22001
sep 02, 2015 1:47:18 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Data truncation: Incorrect datetime value: '’' for column 'Momento' at row 1
sep 02, 2015 1:47:18 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Exception in thread "main" org.hibernate.exception.DataException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:52)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2823)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3323)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:447)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:333)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:335)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1224)
at FechaDAO.insertar(FechaDAO.java:32)
at Prueba.main(Prueba.java:16)
Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '’' for column 'Momento' at row 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2983)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1604)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1519)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1504)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
... 11 more
IIRC for Hibernate5 to map java.time.* no #Temporal annotation is needed/accepted. Hibernate5 have sufficient information to judge the mapping from the type of the property. This is stated in their document.
Java 8 support in Hibernate 5 but this is not portable to other JPA implementations. Add dependencies as below and no more configurations
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
<version>5.1.0.Final</version>
</dependency>
For further reading : Hibernate 5: How to persist LocalDateTime & Co with Hibernate

Categories

Resources