Sequence does not exist exception while using Generation annotation in Hibernate - java

Please see my Model class:
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="STUDENT")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="student_id")
private String studentId;
#Column(name="student_name")
private String studentName;
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
and save it to DB like below:
public static void test4()
{
Student st = new Student();
st.setStudentName("Bitt");
SessionFactory sessionF = new Configuration().configure().buildSessionFactory();
Session session = sessionF.openSession();
session.beginTransaction();
session.save(st);
st = new Student();
st.setStudentName("Rock");
session.save(st);
session.getTransaction().commit();
session.close();
}
the background DB is Oracle11g, Hibernate version is hibernate-core-5.2.10.Final.jar.
from my opinion, if studentId is String data type, hibernate should generate a random string, if studentId is int data type, hibernate should generate a unique number to make sure it is not duplicate in DB, but I got following error message:
Jun 06, 2017 9:20:10 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
Jun 06, 2017 9:20:10 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 06, 2017 9:20:10 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:#16.165.180.124:1521:orcl]
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=hibernate, password=****}
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jun 06, 2017 9:20:10 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jun 06, 2017 9:20:11 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Hibernate: select hibernate_sequence.nextval from dual
Jun 06, 2017 9:20:12 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 2289, SQLState: 42000
Jun 06, 2017 9:20:12 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-02289: sequence does not exist
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
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:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
at org.hibernate.id.enhanced.SequenceStructure$1.getNextValue(SequenceStructure.java:95)
at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:432)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:689)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:681)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:676)
at org.dxc.java.hibernate.main.HibernateDriver.test4(HibernateDriver.java:73)
at org.dxc.java.hibernate.main.HibernateDriver.main(HibernateDriver.java:19)
Caused by: java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:886)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1175)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1296)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3657)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1495)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:71)
... 14 more
so, how can I have hibernate to generate the primary key value automatically for me?

Please change your code to this and check once,
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="student_id")
private Integer studentId;
#GeneratedValue(strategy = GenerationType.AUTO)
This gives you a numeric long value which is auto updated for studentId, each and every record you add.

Related

How can i fix org.hibernate.PersistentObjectException error?

I am trying to connect MySQL Database and insert a new user to the the database.My DB name is bookstoredb and the table name is users.I tried to create model class using hibernate and jpa but i am getting PersistentObjectException error.What am i doing wrong?
The errorlist:
May 16, 2020 7:17:03 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: BookStoreWebsite
...]
May 16, 2020 7:17:04 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.12.Final}
May 16, 2020 7:17:04 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 16, 2020 7:17:04 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager
<clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
May 16, 2020 7:17:04 PM
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
May 16, 2020 7:17:04 PM
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL
[jdbc:mysql://localhost:3306/bookstoredb?serverTimezone=UTC&useSSL=false]
May 16, 2020 7:17:04 PM
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
May 16, 2020 7:17:04 PM
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
May 16, 2020 7:17:04 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
May 16, 2020 7:17:04 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Exception in thread "main" javax.persistence.PersistenceException:
org.hibernate.PersistentObjectException: detached entity passed to persist:
com.bookstore.entity.Users
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:149)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:789)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:767)
at UsersTest.main(UsersTest.java:17)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist:
com.bookstore.entity.Users
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:124)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:782)
... 2 more
My persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="BookStoreWebsite">
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/bookstoredb?serverTimezone=UTC&useSSL=false" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
</properties>
</persistence-unit>
</persistence>
My POJO class:
package com.bookstore.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Users {
private Integer userId;
private String email;
private String fullName;
private String password;
#Column(name="user_id")
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="full_name")
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
My POJO test class:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.bookstore.entity.Users;
public class UsersTest {
public static void main(String[] args) {
Users user1=new Users();
user1.setEmail("dagidirnilgun#gmail.com");
user1.setFullName("Nilgün Dağıdır");
user1.setPassword("helloworld");
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("BookStoreWebsite");
EntityManager entityManager=entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(user1);
entityManager.getTransaction().commit();
entityManager.close();
entityManagerFactory.close();
System.out.println("Successfully inserted");
}
}
My packages:
You have defined fullName to be your unique key of Users, but at the same time use a #GeneratedValue(strategy=GenerationType.IDENTITY). In your test you manually set this value and thus persist fails. The persist operation (as the name suggests) is intended for brand new objects with no id set, but since you set your fullName you are bascially trying to persist a detached entity.
I edited users table in bookstoredb like this:
And i fixed my POJO class like this:
package com.bookstore.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Users {
private Integer userId;
private String email;
private String fullName;
private String password;
#Column(name="user_id")
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="full_name")
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

I am working with Hibernate and I'm trying to add primary key in the table created by hibernate to store collection

The whole code worked before I wrote collectionID, but after that it created table named sequence-gen and it tries to add values(1)
Here's how my Entity looks like,
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import org.hibernate.annotations.CollectionId;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
#Entity
public class Student {
public int getStudent_id() {
return student_id;
}
public void setStudent_id(int student_id) {
this.student_id = student_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getCGPA() {
return CGPA;
}
public void setCGPA(float cGPA) {
CGPA = cGPA;
}
#Id #GeneratedValue
private int student_id;
private String name;
private float CGPA;
/*
* #Embedded private Address address;
*/
#ElementCollection
#JoinTable(name = "Address",
joinColumns = #JoinColumn(name="student_id")
)
#GenericGenerator(name = "sequence-gen", strategy = "sequence")
#CollectionId(columns = { #Column(name="AddressTable_ID") }, generator = "sequence-gen", type = #Type(type="int"))
private Collection<Address> listOfAddress=new ArrayList<Address>();
public Collection<Address> getListOfAddress() {
return listOfAddress;
}
public void setListOfAddress(Collection<Address> listOfAddress) {
this.listOfAddress = listOfAddress;
}
/*
* public Address getAddress() { return address; } public void
* setAddress(Address address) { this.address = address; }
*/
}
And here's my clienttest looks like,
import java.util.HashSet;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args) {
Configuration con = new Configuration().configure().addAnnotatedClass(Student.class);
SessionFactory sf = con.buildSessionFactory();
// Inserting Data into table...
Student s = new Student();
//s.setStudent_id(2);
s.setName("Yash");
s.setCGPA(8.80f);
Address address1=new Address();
address1.setCity("Rajkot");
address1.setPincode("360002");
address1.setStreet("Sorathiyawadi");
/* s.setAddress(address1); */
Address address2=new Address();
address2.setCity("Ahemdabad");
address2.setPincode("380002");
address2.setStreet("ISCON Mall");
/* s.setAddress(address2); */
HashSet<Address> sets=new HashSet<Address>();
sets.add(address1);
sets.add(address2);
s.setListOfAddress(sets);
//Transaction
Session session = sf.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
s = null;
// Retriving Information...
Session s2 = sf.openSession();
s2.beginTransaction();
s = s2.get(Student.class, 1);
System.out.println(s.getName());
}
}
This is my model:
import javax.persistence.Embeddable;
#Embeddable
public class Address {
private String city;
private String pincode;
private String street;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
And here is my config file:
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3308/yash
root
org.hibernate.dialect.MySQL5Dialect
true
create
What error i'm getting shows like...
Mar 31, 2020 8:19:19 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.4.12.Final
Mar 31, 2020 8:19:20 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
Mar 31, 2020 8:19:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Mar 31, 2020 8:19:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3308/yash]
Mar 31, 2020 8:19:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root}
Mar 31, 2020 8:19:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Mar 31, 2020 8:19:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Tue Mar 31 08:19:20 IST 2020 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, 2020 8:19:20 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate: drop table if exists Address
Mar 31, 2020 8:19:20 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#63884e4] 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.
Hibernate: drop table if exists hibernate_sequence
Hibernate: drop table if exists sequence-gen
Hibernate: drop table if exists Student
Mar 31, 2020 8:19:20 AM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error executing DDL "drop table if exists sequence-gen" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "drop table if exists sequence-gen" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:375)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:359)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:241)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:154)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:126)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:112)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:145)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:314)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:468)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at Main.main(Main.java:12)
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 '-gen' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:790)
at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:675)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
... 13 more
Hibernate: create table Address (student_id integer not null, city varchar(255), pincode varchar(255), street varchar(255), AddressTable_ID integer not null, primary key (AddressTable_ID)) engine=MyISAM
Mar 31, 2020 8:19:20 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#6cd3ad8a] 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.
Hibernate: create table hibernate_sequence (next_val bigint) engine=MyISAM
Hibernate: insert into hibernate_sequence values ( 1 )
Hibernate: create table sequence-gen (next_val bigint) engine=MyISAM
Mar 31, 2020 8:19:20 AM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error executing DDL "create table sequence-gen (next_val bigint) engine=MyISAM" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table sequence-gen (next_val bigint) engine=MyISAM" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:439)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:423)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:314)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:156)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:314)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:468)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at Main.main(Main.java:12)
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 '-gen (next_val bigint) engine=MyISAM' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:790)
at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:675)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
... 13 more
Hibernate: insert into sequence-gen values ( 1 )
Mar 31, 2020 8:19:20 AM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error executing DDL "insert into sequence-gen values ( 1 )" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "insert into sequence-gen values ( 1 )" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:439)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:423)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:314)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:156)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:314)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:468)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at Main.main(Main.java:12)
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 '-gen values ( 1 )' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:790)
at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:675)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
... 13 more
Hibernate: create table Student (student_id integer not null, CGPA float not null, name varchar(255), primary key (student_id)) engine=MyISAM
Hibernate: alter table Address add constraint FK4q6j38bhikrv1pjbmde52gg7 foreign key (student_id) references Student (student_id)
Mar 31, 2020 8:19:20 AM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Tue Mar 31 08:19:20 IST 2020 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.
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into Student (CGPA, name, student_id) values (?, ?, ?)
Hibernate: select next_val as id_val from sequence-gen for update
Mar 31, 2020 8:19:21 AM org.hibernate.id.enhanced.TableStructure$1$1 execute
ERROR: could not read a hi value
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 '-gen for update' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:960)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1019)
at org.hibernate.id.enhanced.TableStructure.executeQuery(TableStructure.java:216)
at org.hibernate.id.enhanced.TableStructure.access$300(TableStructure.java:46)
at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:138)
at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:126)
at org.hibernate.jdbc.WorkExecutor.executeReturningWork(WorkExecutor.java:55)
at org.hibernate.jdbc.AbstractReturningWork.accept(AbstractReturningWork.java:34)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:57)
at org.hibernate.id.enhanced.TableStructure$1.getNextValue(TableStructure.java:125)
at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:523)
at org.hibernate.collection.internal.PersistentIdentifierBag.preInsert(PersistentIdentifierBag.java:406)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1311)
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:52)
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:684)
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:1352)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:443)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3202)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2370)
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 Main.main(Main.java:36)
Mar 31, 2020 8:19:21 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1064, SQLState: 42000
Mar 31, 2020 8:19:21 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: 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 '-gen for update' at line 1
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: error performing isolated work
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:1356)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:443)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3202)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2370)
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 Main.main(Main.java:36)
Caused by: org.hibernate.exception.SQLGrammarException: error performing isolated work
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.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:79)
at org.hibernate.id.enhanced.TableStructure$1.getNextValue(TableStructure.java:125)
at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:523)
at org.hibernate.collection.internal.PersistentIdentifierBag.preInsert(PersistentIdentifierBag.java:406)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1311)
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:52)
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:684)
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:1352)
... 9 more
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 '-gen for update' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:960)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1019)
at org.hibernate.id.enhanced.TableStructure.executeQuery(TableStructure.java:216)
at org.hibernate.id.enhanced.TableStructure.access$300(TableStructure.java:46)
at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:138)
at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:126)
at org.hibernate.jdbc.WorkExecutor.executeReturningWork(WorkExecutor.java:55)
at org.hibernate.jdbc.AbstractReturningWork.accept(AbstractReturningWork.java:34)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:57)
... 23 more
omit the "-" from "sequence-gen" and try it again

Hibernate is adding class name before column name automatically generating Foreign key exception

I am a beginner in Hibernate. I have two tables, "Cities" and "States". My City class is the following:
package model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.persistence.Version;
#Entity
#Table(name="Cities",uniqueConstraints= {#UniqueConstraint(columnNames= {"city_id"})})
public class Cities {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int city_id;
#Column(name="CITY_NAME",nullable=true,unique=false)
private String city_name;
#Column(name="POPULATION",nullable=true,unique=false)
private int population;
#Column(name="TS_CNT",nullable=false,unique=true)
#Version
private int ts_cnt;
public int getCity_id() {
return city_id;
}
public void setCity_id(int city_id) {
this.city_id = city_id;
}
public String getCity_name() {
return city_name;
}
public void setCity_name(String city_name) {
this.city_name = city_name;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public int getTs_cnt() {
return ts_cnt;
}
public void setTs_cnt(int ts_cnt) {
this.ts_cnt = ts_cnt;
}
}
And following is my "State" class.
package model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table
public class State {
#Id
#Column(name = "state_id", nullable = false, unique = true)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int state_id;
#Column(name = "state_name", nullable = false, unique = true)
private String state_name;
#Column(name = "state_capital", nullable = false, unique = true)
private String state_capital;
#OneToOne
private Cities cities;
public int getState_id() {
return state_id;
}
public void setState_id(int state_id) {
this.state_id = state_id;
}
public String getState_name() {
return state_name;
}
public void setState_name(String state_name) {
this.state_name = state_name;
}
public String getState_capital() {
return state_capital;
}
public void setState_capital(String state_capital) {
this.state_capital = state_capital;
}
public Cities getCities() {
return cities;
}
public void setCities(Cities cities) {
this.cities = cities;
}
}
Now when I run this code, like the following, I get exception:
package citiutilities;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import interfaces.Dbops;
import model.Cities;
import model.State;
public class InsertCities implements Dbops {
public static void main(String[] args) {
Cities citi1 = new Cities();
State state1 = new State();
InsertCities ic = new InsertCities();
ic.insertCities(citi1, state1);
}
public void insertCities(Cities citi1, State state1) {
citi1.setCity_id(100);
citi1.setCity_name("Patna");
citi1.setPopulation(180000);
state1.setState_id(100);
state1.setState_capital("Patna");
state1.setState_name("Bihar");
state1.setCities(citi1);
Session session = CityDbUtil.createSession();
session.beginTransaction();
try {
session.save(state1);
session.getTransaction().commit();
System.out.println("The city that was saved is :: " + citi1.getCity_id());
} catch (HibernateException he) {
session.getTransaction().rollback();
he.printStackTrace();
}
finally {
session.close();
}
}
}
The stack trace is the following:
Oct 05, 2018 9:45:27 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.17.Final}
Oct 05, 2018 9:45:27 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Oct 05, 2018 9:45:27 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Oct 05, 2018 9:45:27 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Oct 05, 2018 9:45:27 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost/subirdb]
Oct 05, 2018 9:45:27 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=postgres, password=****}
Oct 05, 2018 9:45:27 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Oct 05, 2018 9:45:27 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Oct 05, 2018 9:45:28 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
Oct 05, 2018 9:45:28 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
Oct 05, 2018 9:45:28 PM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#5fa07e12
Oct 05, 2018 9:45:29 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#2b95e48b] 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.
Hibernate:
create table Cities (
city_id int4 not null,
CITY_NAME varchar(255),
POPULATION int4,
TS_CNT int4 not null,
primary key (city_id)
)
Hibernate:
create table State (
state_id serial not null,
state_capital varchar(255) not null,
state_name varchar(255) not null,
cities_city_id int4,
primary key (state_id)
)
Hibernate:
alter table Cities
drop constraint UK_lyvuwacb89kupauxjk1103pjl
Hibernate:
alter table Cities
add constraint UK_lyvuwacb89kupauxjk1103pjl unique (TS_CNT)
Hibernate:
alter table State
drop constraint UK_jv8xyklsot1gudi8bfo3hrdkj
Hibernate:
alter table State
add constraint UK_jv8xyklsot1gudi8bfo3hrdkj unique (state_capital)
Hibernate:
alter table State
drop constraint UK_sh9wvgcb2q4h69yjib264nlh4
Hibernate:
alter table State
add constraint UK_sh9wvgcb2q4h69yjib264nlh4 unique (state_name)
Hibernate:
alter table State
add constraint FKmcjxnu2cw7ax2uefyvp55saky
foreign key (cities_city_id)
references Cities
Oct 05, 2018 9:45:29 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Oct 05, 2018 9:45:29 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost/subirdb]
Oct 05, 2018 9:45:29 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=postgres, password=****}
Oct 05, 2018 9:45:29 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Oct 05, 2018 9:45:29 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Oct 05, 2018 9:45:30 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
Oct 05, 2018 9:45:30 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
Oct 05, 2018 9:45:30 PM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#5fa07e12
Oct 05, 2018 9:45:30 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#5cbf9e9f] 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.
Hibernate:
insert
into
State
(cities_city_id, state_capital, state_name)
values
(?, ?, ?)
Oct 05, 2018 9:45:30 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 23503
Oct 05, 2018 9:45:30 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ERROR: insert or update on table "state" violates foreign key constraint "fkmcjxnu2cw7ax2uefyvp55saky"
Detail: Key (cities_city_id)=(100) is not present in table "cities".
org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:112)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2933)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3524)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:637)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:692)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:684)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:679)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:355)
at com.sun.proxy.$Proxy27.save(Unknown Source)
at citiutilities.InsertCities.insertCities(InsertCities.java:29)
at citiutilities.InsertCities.main(InsertCities.java:14)
Caused by: org.postgresql.util.PSQLException: ERROR: insert or update on table "state" violates foreign key constraint "fkmcjxnu2cw7ax2uefyvp55saky"
Detail: Key (cities_city_id)=(100) is not present in table "cities".
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2477)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2190)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:300)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:428)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:354)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:169)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:136)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
... 29 more
What I observed in this particular case is that, somehow system is creating a column Cities_city_id in the state table whereas the intention was that system creates a column with the name city_id. According to me this is creating the problem because this column does not exist in the cities table. But I do not understand why system is manipulating the name. I tried to search in internet but in vain.
Observed 2 issues while running the code
state1.setState_id(100);
citi1.setCity_id(100);
These two fields has already #GeneratedValue Tag , meaning no need to explicitly set it.
Secondly, Once i resolved the above , the second error is
object references an unsaved transient instance - save the transient instance before flushing
For this, update the State.java. Adding CascadeType.ALL helps save the City Information while saving State Info.
#OneToOne(cascade =CascadeType.ALL)
private Cities cities;
Regarding the Cities_city_id , thats the foreign key
FOREIGN KEY (`cities_city_id`) REFERENCES `Cities` (`city_id`)

Hibernate: Unable to locate persister integracion.entidades.Bodega

Good evening guys!
Context: As i said in my first question (two days ago) i new with Hibernate.
In the last question the people adviced me to used Maven to work better with the dependancy. I did it and i'm pleased.
I think that i have done (almost) all what i have to do to do work a Hibernate project. The problem that i have encountered is that i dont get to persist all the entities.
The console says me that:
dic 20, 2016 12:21:34 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.5.Final}
dic 20, 2016 12:21:34 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
dic 20, 2016 12:21:34 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
dic 20, 2016 12:21:34 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
dic 20, 2016 12:21:34 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/vinoteca]
dic 20, 2016 12:21:34 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
dic 20, 2016 12:21:34 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
dic 20, 2016 12:21:34 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Tue Dec 20 00:21:34 CET 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.
dic 20, 2016 12:21:34 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
dic 20, 2016 12:21:35 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
dic 20, 2016 12:21:35 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/vinoteca]
dic 20, 2016 12:21:35 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
dic 20, 2016 12:21:35 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
dic 20, 2016 12:21:35 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Tue Dec 20 00:21:35 CET 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.
dic 20, 2016 12:21:35 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Exception in thread "main" org.hibernate.UnknownEntityTypeException: Unable to locate persister: integracion.entidades.Bodega
at org.hibernate.metamodel.internal.MetamodelImpl.locateEntityPersister(MetamodelImpl.java:637)
at org.hibernate.internal.SessionImpl.locateEntityPersister(SessionImpl.java:2920)
at org.hibernate.internal.SessionImpl.access$1800(SessionImpl.java:204)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2671)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2657)
at org.hibernate.internal.SessionImpl.byId(SessionImpl.java:1185)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:1058)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:355)
at com.sun.proxy.$Proxy18.get(Unknown Source)
at integracion.dao.GenericDAOImpl.get(GenericDAOImpl.java:48)
at negocio.Main.main(Main.java:32)
And my entities are these:
package integracion.entidades;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Table;
#DynamicUpdate
#Table(appliesTo = "bodega")
public class Bodega implements Serializable {
#Id
#Column(name="id")
private int id;
#Column(name="nombre")
private String nombre;
#OneToMany(mappedBy="bodega",cascade= CascadeType.ALL)
private Set<Vino> vinos;
public Bodega(){
}
public Bodega(int id, String nombre) {
this.id = id;
this.nombre = nombre;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
package integracion.entidades;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Id;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Table;
#DynamicUpdate
#Table(appliesTo = "Denominacion")
public class Denominacion implements Serializable{
#Id
#Column(name="id")
private int id;
#Column(name="nombre")
private String nombre;
public Denominacion(){
}
public Denominacion(int id, String nombre) {
this.id = id;
this.nombre = nombre;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
package integracion.entidades;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Table;
#DynamicUpdate
#Table(appliesTo = "vino")
public class Vino implements Serializable{
#Id
#Column(name="id")
private int id;
#ManyToOne
#JoinColumn(name="id_bodega")
private int id_bodega;
#ManyToOne
#JoinColumn(name="id_denominacion")
private int id_denominacion;
#Column(name="nombre")
private String nombre;
#Column(name="anho")
private int anho;
/*
* <many-to-one name="bodega">
<column name="id_bodega" />
</many-to-one>
*/
public Vino(){
}
public Vino(int id, int id_bodega, int id_denominacion, String nombre, int anho) {
this.id = id;
this.id_bodega = id_bodega;
this.id_denominacion = id_denominacion;
this.nombre = nombre;
this.anho = anho;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getId_bodega() {
return id_bodega;
}
public void setId_bodega(int id_bodega) {
this.id_bodega = id_bodega;
}
public int getId_denominacion() {
return id_denominacion;
}
public void setId_denominacion(int id_denominacion) {
this.id_denominacion = id_denominacion;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public int getAnho() {
return anho;
}
public void setAnho(int anho) {
this.anho = anho;
}
}
And my mapping 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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/vinoteca</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.show_sql">true</property>
<mapping class="src.main.java.integracion.entidades.Bodega.java"/>
<mapping class="src.main.java.integracion.entidades.Denominacion.java"/>
<mapping class="src.main.java.integracion.entidades.Vino.java"/>
</session-factory>
</hibernate-configuration>
Here i have the tree project:
http://imgur.com/a/fZ6qn
I have 2 theories:
First, it could be the hibernate.cfg.xml the problem cause (maybe) the paths of the mapping class tag are wrong..
Second, maybe the annotation entities are wrong because I could have made a mistake writing the relation(1:1, 1:n, n:N)..
Guys, all the help you give me i thank you!
regards!

JavaFX desktop app - Using HSQLDB (embedded) and Hibernate

Is there good tutorial on using HSQLDB, Hibernate and JavaFX. I am using eclipse as my IDE. My Project model has variables defined like this:
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PROJECTID")
private long projectId;
#Column(name = "PROJECTNAME")
private final StringProperty projectName;
#Column(name = "PROJECTJIBP")
private final StringProperty projectJIBP;
Is this valid way of using Hibernate with JavaFX ?
persistance.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
<class> handwrittencode.eiar.model.Project</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="show_sql" value="true"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
</persistence>
I am getting this error message:
Jun 28, 2014 7:53:27 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Jun 28, 2014 7:53:27 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Jun 28, 2014 7:53:27 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Jun 28, 2014 7:53:27 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: test
...]
Jun 28, 2014 7:53:27 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
Jun 28, 2014 7:53:27 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 28, 2014 7:53:27 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jun 28, 2014 7:53:28 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Jun 28, 2014 7:53:28 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Jun 28, 2014 7:53:28 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [org.hsqldb.jdbcDriver] at URL [jdbc:hsqldb:mem:test]
Jun 28, 2014 7:53:28 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=sa}
Jun 28, 2014 7:53:28 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Jun 28, 2014 7:53:28 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jun 28, 2014 7:53:28 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.HSQLDialect
Jun 28, 2014 7:53:28 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000422: Disabling contextual LOB creation as connection was null
Initial SessionFactory creation failed.javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to build Hibernate SessionFactory
Exception in Application constructor
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:367)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:305)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Unable to construct Application instance: class handwrittencode.eiar.MainApp
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:884)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:56)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:158)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
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:408)
at com.sun.javafx.application.LauncherImpl$7.run(LauncherImpl.java:791)
at com.sun.javafx.application.PlatformImpl$7.run(PlatformImpl.java:335)
at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:301)
at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:298)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$6.run(PlatformImpl.java:298)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39)
at com.sun.glass.ui.win.WinApplication$4$1.run(WinApplication.java:112)
... 1 more
Caused by: java.lang.ExceptionInInitializerError
at handwrittencode.eiar.util.EntityManagerUtil.<clinit>(EntityManagerUtil.java:16)
at handwrittencode.eiar.MainApp.<init>(MainApp.java:32)
... 15 more
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1225)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.access$600(EntityManagerFactoryBuilderImpl.java:119)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:853)
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:75)
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 handwrittencode.eiar.util.EntityManagerUtil.<clinit>(EntityManagerUtil.java:12)
... 16 more
Caused by: org.hibernate.MappingException: Could not determine type for: javafx.beans.property.StringProperty, at table: PROJECT, for columns: [org.hibernate.mapping.Column(projectAddress)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:336)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:310)
at org.hibernate.mapping.Property.isValid(Property.java:241)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:496)
at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1358)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1849)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
... 24 more
Exception running application handwrittencode.eiar.MainApp
EDIT
package handwrittencode.eiar.model;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import handwrittencode.eiar.util.LocalDateAdapter;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
#Entity
#Table(name = "PROJECT")
public class Project {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PROJECTID")
private long projectId;
private final StringProperty projectName;
private final StringProperty projectJIBP;
private final StringProperty projectState;
private final StringProperty projectAddress;
private final StringProperty projectManager;
private final ObjectProperty<LocalDate> projectCreated;
private final ObjectProperty<LocalDate> projectStart;
private final ObjectProperty<LocalDate> projectEnd;
public Project()
{
this(null,null,null,null,null);
}
public Project(String projectName, String projectJIBP, String projectState, String projectAddress, String projectManager)
{
this.projectName = new SimpleStringProperty(projectName);
this.projectJIBP = new SimpleStringProperty(projectJIBP);
this.projectState = new SimpleStringProperty(projectState);
this.projectAddress = new SimpleStringProperty(projectAddress);
this.projectManager = new SimpleStringProperty(projectManager);
this.projectCreated = new SimpleObjectProperty<LocalDate>(LocalDate.of(1999, 2, 21));
this.projectStart = new SimpleObjectProperty<LocalDate>(LocalDate.of(1999, 2, 21));
this.projectEnd = new SimpleObjectProperty<LocalDate>(LocalDate.of(1999, 2, 21));
}
#Column(name = "PROJECTNAME")
public String getProjectName() {
return projectName.get();
}
public void setProjectName(String projectName) {
this.projectName.set(projectName);
}
public StringProperty projectNameProperty() {
return this.projectName;
}
/**/
#Column(name = "PROJECTJIBP")
public String getProjectJIBP(){
return projectJIBP.get();
}
public void setProjectJIBP(String projectJIBP) {
this.projectJIBP.set(projectJIBP);
}
public StringProperty projectJIBPProperty() {
return this.projectJIBP;
}
/**/
#Column(name = "PROJECTSTATE")
public String getProjectState(){
return projectState.get();
}
public void setProjectState(String projectState) {
this.projectState.set(projectState);
}
public StringProperty projectStateProperty() {
return this.projectState;
}
/**/
#Column(name = "PROJECTADDRESS")
public String getProjectAddress(){
return projectAddress.get();
}
public void setProjectAddress(String projectAddress) {
this.projectAddress.set(projectAddress);
}
public StringProperty projectAddressProperty() {
return this.projectAddress;
}
/**/
#Column(name = "PROJECTMANAGER")
public String getProjectManager(){
return projectManager.get();
}
public void setProjectManager(String projectManager) {
this.projectManager.set(projectManager);
}
public StringProperty projectManagerProperty() {
return this.projectManager;
}
/**/
#XmlJavaTypeAdapter(LocalDateAdapter.class)
public LocalDate getProjectCreated() {
return projectCreated.get();
}
public void setProjectCreated(LocalDate projectCreated) {
this.projectCreated.set(projectCreated);
}
public ObjectProperty<LocalDate> projectCreatedProperty() {
return projectCreated;
}
/**/
#XmlJavaTypeAdapter(LocalDateAdapter.class)
public LocalDate getProjectStart() {
return projectStart.get();
}
public void setProjectStart(LocalDate projectStart) {
this.projectStart.set(projectStart);
}
public ObjectProperty<LocalDate> projectStartProperty() {
return projectStart;
}
/**/
#XmlJavaTypeAdapter(LocalDateAdapter.class)
public LocalDate getProjectEnd() {
return projectEnd.get();
}
public void setProjectEnd(LocalDate projectEnd) {
this.projectEnd.set(projectEnd);
}
public ObjectProperty<LocalDate> projectEndProperty() {
return projectEnd;
}
}
Is this valid way of using Hibernate with JavaFX ?
No: use property access instead of field access:
private final StringProperty projectName;
#Column(name = "PROJECTNAME")
public final String getProjectName() {
return projectName.get();
}
public final void setProjectName(String projectName) {
this.projectName.set(projectName);
}
public StringProperty projectNameProperty() {
return projectName;
}
etc...
This enables Hibernate to determine the types from the return types of the get methods, rather than from the types of the actual fields; so it can persist Strings instead of StringPropertys, and so on.
See Steven Van Impe's blog and my blog

Categories