JavaFX desktop app - Using HSQLDB (embedded) and Hibernate - java

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

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

How to implement mapping in hibernate using annotation?

I am trying to implement OneToMany and ManyToOne mapping in hibernate but I got error in dispatcher-servlet.xml while adding mapping class.
It return error:
> cvc-complex-type.2.4.a: Invalid content was found starting with
> element 'mapping'. "http:// www.springframework.org/schema/beans"]}'
> is expected.
dispatcher-servlet.xml file:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.tushar.hibernate.model.User</value>
<value>com.tushar.hibernate.model.Sender</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.c3p0.max_statements">${connectionpool.maximum.statements}</prop>
</props>
</property>
<mapping class="com.tushar.hibernate.model.User" /> <!-- This is the line which return an error -->
<mapping class="com.tushar.hibernate.model.Sender" />
</bean>
Model Class User:
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue
#Column(name = "u_id")
private int userId;
#Column(name = "name")
private String name;
#Column(name = "mobile")
private String mobile;
#Column(name = "email")
private String email;
private Set<Sender> userSenderId = new HashSet<Sender>(0);
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name = "user_sender", joinColumns = { #JoinColumn(name = "u_id") }, inverseJoinColumns = { #JoinColumn(name = "s_id") })
public Set<Sender> getUserSenderId() {
return userSenderId;
}
public void setUserSenderId(Set<Sender> userSenderId) {
this.userSenderId = userSenderId;
}
}
Model Class Sender:
#Entity
#Table(name = "sender")
public class Sender {
#Id
#GeneratedValue
#Column(name = "s_id")
private int sId;
#Column(name = "sender_id")
private String senderId;
#ManyToOne(cascade=CascadeType.ALL)
private User user;
public int getsId() {
return sId;
}
public void setsId(int sId) {
this.sId = sId;
}
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
This are the two class that I want to map each other
#OneToMany for User to Sender
And #ManyToOne for Sender to User
But after running project it return some errors like:
Aug 05, 2017 10:20:43 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/spring-hibernate] has started
Aug 05, 2017 10:20:43 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc
SEVERE: The web application [/spring-hibernate] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
Aug 05, 2017 10:20:43 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
SEVERE: The web application [/spring-hibernate] appears to have started a thread named [MySQL Statement Cancellation Timer] but has failed to stop it. This is very likely to create a memory leak.
Aug 05, 2017 10:20:44 PM org.apache.catalina.startup.TldConfig execute
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Aug 05, 2017 10:20:44 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Aug 05, 2017 10:20:44 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Aug 05, 2017 10:20:45 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: user, for columns: [org.hibernate.mapping.Column(userSenderId)]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:684)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1282)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1195)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1085)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5349)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5641)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:4119)
at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:425)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1341)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1542)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1552)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1552)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1520)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: user, for columns: [org.hibernate.mapping.Column(userSenderId)]
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.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:343)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:431)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:416)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
... 30 more
Aug 05, 2017 10:20:45 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [dispatcher] in web application [/spring-hibernate] threw load() exception
org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: user, for columns: [org.hibernate.mapping.Column(userSenderId)]
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.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:343)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:431)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:416)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:684)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1282)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1195)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1085)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5349)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5641)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:4119)
at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:425)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1341)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1542)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1552)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1552)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1520)
at java.lang.Thread.run(Thread.java:745)
Aug 05, 2017 10:20:45 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/spring-hibernate] is completed
Above error returns when I tried to do mapping in model without writing mapping property in dispatcher-servlet.xml file.
You have already declared the model classes in the xml:
<list>
<value>com.tushar.hibernate.model.User</value>
<value>com.tushar.hibernate.model.Sender</value>
</list>
You don't need to add the mapping entries, and also this configuration is used by spring and mapping tag in not allowed here. If you are using hibernate.cfg.xml file then you can declare your mappings there(Only if you are not using annotations).
You just need to add #Entity annotation on top of your model classes.
<mapping class="com.tushar.hibernate.model.User" />
this tag is not present in <bean> tag..
If you have hibernate configuration file then use following tag to configure that cfg file in sessionfactory bean of spring cfg file-
<property name="configLocation" value="hibernate_cfg_file_name"/>
if you remove <mapping> tag then may your program work....
try it...

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.

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!

Categories