Hibernate: Unable to locate persister integracion.entidades.Bodega - java

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!

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;
}
}

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`)

Sequence does not exist exception while using Generation annotation in Hibernate

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.

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

Hibernate mapping exception: unknown entity

I am new to Java and just started learning Hibernate from an online tutorial. I have created java code with Hibernate but after that i have been failing to test run.
I have database table "users" in MySQL Database "test". when i try to insert a record it gives me this error. Cant find the exact reason..
Stack:
710 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
org.hibernate.MappingException: Unknown entity: in.shivasoft.pojo.Users
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:580)
at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1365)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:121)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:562)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:550)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:546)
at in.shivasoft.test.TestMain.saveRecord(TestMain.java:33)
at in.shivasoft.test.TestMain.main(TestMain.java:19)
my Users.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 entity-name="Users" name="in.shivasoft.pojo.Users" table="Users">
<meta attribute="description">This class is used to save the info about users</meta>
<id column="UserId" name="UserId" type="long"/>
<property column="FName" name="FName" type="string"/>
<property column="LName" name="LName" type="string"/>
<property column="UserTypeId" name="UserTypeId" type="long"/>
<property column="UserName" name="UserName" type="string"/>
<property column="Email" name="Email" type="string"/>
<property column="Pwd" name="Pwd" type="string"/>
<property column="Note" name="Note" type="string"/>
<property column="IsActive" name="IsActive" type="boolean"/>
</class>
</hibernate-mapping>
Hibernate Configuration(hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.password">1234</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
<property name="hibernate.connection.username">root</property**strong text**>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<mapping resource="in/shivasoft/pojo/Users.hbm.xml"/>
</session-factory>
</hibernate-configuration>
This is Entity class created by Hibernate code Generation
package in.shivasoft.pojo;
// Generated Sep 27, 2013 11:48:09 AM by Hibernate Tools 4.0.0
/**
* Users generated by hbm2java
*/
public class Users implements java.io.Serializable {
private long UserId;
private String FName;
private String LName;
private long UserTypeId;
private String UserName;
private String Email;
private String Pwd;
private String Note;
private boolean IsActive;
public Users() {
}
public Users(long UserId) {
this.UserId = UserId;
}
public Users(long UserId, String FName, String LName, long UserTypeId,
String UserName, String Email, String Pwd, String Note,
boolean IsActive) {
this.UserId = UserId;
this.FName = FName;
this.LName = LName;
this.UserTypeId = UserTypeId;
this.UserName = UserName;
this.Email = Email;
this.Pwd = Pwd;
this.Note = Note;
this.IsActive = IsActive;
}
public long getUserId() {
return this.UserId;
}
public void setUserId(long UserId) {
this.UserId = UserId;
}
public String getFName() {
return this.FName;
}
public void setFName(String FName) {
this.FName = FName;
}
public String getLName() {
return this.LName;
}
public void setLName(String LName) {
this.LName = LName;
}
public long getUserTypeId() {
return this.UserTypeId;
}
public void setUserTypeId(long UserTypeId) {
this.UserTypeId = UserTypeId;
}
public String getUserName() {
return this.UserName;
}
public void setUserName(String UserName) {
this.UserName = UserName;
}
public String getEmail() {
return this.Email;
}
public void setEmail(String Email) {
this.Email = Email;
}
public String getPwd() {
return this.Pwd;
}
public void setPwd(String Pwd) {
this.Pwd = Pwd;
}
public String getNote() {
return this.Note;
}
public void setNote(String Note) {
this.Note = Note;
}
public boolean isIsActive() {
return this.IsActive;
}
public void setIsActive(boolean IsActive) {
this.IsActive = IsActive;
}
}
This is my TestMain.Java
package in.shivasoft.test;
import in.shivasoft.pojo.Users;
import in.shivasoft.util.HibernateUtil;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class TestMain {
/**
* #param args
*/
public static void main(String[] args) {
TestMain obj = new TestMain();
obj.saveRecord();
obj.getList();
}
public void saveRecord()
{
Users u = new Users(0, "Jitendra", "Zaa", 1, "jitendra.zaa", "jitendra.zaa#shivasoft.in", "test", "this is note", true);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try
{
transaction = session.beginTransaction();
session.save(u);
transaction.commit();
System.out.println("Data Saved");
}catch(Exception e)
{
e.printStackTrace();
}finally{session.close();}
}
public void updateUser(long UserId)
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try
{
transaction = session.beginTransaction();
Users u = (Users)session.get(Users.class,UserId);
u.setFName("ShivaSoft");
transaction.commit();
System.out.println("Data Updated");
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
session.close();
}
}
public void getList()
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try
{
transaction = session.beginTransaction();
List<Users> uList = List<Users> uList = Session.createCriteria(Users.class).list();
for(Users u : uList)
{
System.out.println("First Name - "+u.getFName());
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
session.close();
}
}
}
This is log for session Factory Dont know if there is problem with it..
10 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.3.1.GA
13 [main] INFO org.hibernate.cfg.Environment - loaded properties from resource hibernate.properties: {hibernate.bytecode.use_reflection_optimizer=false}
15 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
19 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
61 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
61 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
128 [main] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : in/shivasoft/pojo/Users.hbm.xml
197 [main] INFO org.hibernate.cfg.HbmBinder - Mapping class: Users -> users
208 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
256 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
256 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20
256 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false
262 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: org.gjt.mm.mysql.Driver at URL: jdbc:mysql://localhost/test
262 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=root, password=****}
499 [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: MySQL, version: 5.6.14-log
499 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.0 ( $Date: 2007-04-05 23:56:05 +0200 (Thu, 05 Apr 2007) $, $Revision: 6376 $ )
515 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
518 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions)
519 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
519 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
519 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
520 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
520 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
520 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
520 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
520 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto
521 [main] INFO org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2
521 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
521 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
521 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
521 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
521 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
523 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
523 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
523 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled
523 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
523 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled
523 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
523 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
523 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
527 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled
528 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
528 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
528 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled
568 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
737 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
remove 'entity-name' attribute in user.hbm.xml. it will work fine.
DO like this "class name="in.shivasoft.pojo.Users" table="Users"
here and here you wil get to know why you need to remove that 'entity-name' attribute name

Categories