save method in hibernate not inserting immediately - java

As per the document i read here it says :
Hibernate save method returns the generated id immediately, this is possible because primary object is saved as soon as save method is invoked.
But in my example below, i have fired the save method and then kept the thread on sleep for 1 minute.
Within this timespace when i check the database the person_o table doesnt show any data in it. why isnt it showing the age and name value in it immediately after save. though it appears after the commit is executed once sleep is over .
addperson.java:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class addperson {
public static void main(String as[])
{
//Activate Hibernate Software
Configuration cfg=new Configuration();
//make hibernate software locating and reading cfg file
cfg=cfg.configure("/hibernate.cfg.xml");
//create SessionFactory obj
SessionFactory factory=cfg.buildSessionFactory();
//create HB session obj
Session session=factory.openSession();
Transaction tx = session.beginTransaction();
try {
// Create a person
person person = new person();
person.setName("Luna");
person.setAge(33);
Integer key = (Integer) session.save(person);
System.out.println("Primary Key : " + key);
person.setId(key);
System.out.println("---going for sleep---");
Thread.sleep(60000);
// Create the address for the person
personaddress address = new personaddress();
address.setAddressLine1("Lunaris");
address.setCity("Twinkle");
address.setState("MA");
address.setZipCode(10308);
address.setPerson(person);
person.setAddress(address);
key = (Integer) session.save(address);
System.out.println("Primary Key again : " + key);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
session.close();
}
}
}
person.java
import java.io.Serializable;
public class person implements Serializable {
private static final long serialVersionUID = -9127358545321739524L;
private int id;
private String name;
private int age;
private personaddress address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public personaddress getAddress() {
return address;
}
public void setAddress(personaddress address) {
this.address = address;
}
}
personaddress.java
import java.io.Serializable;
public class personaddress implements Serializable {
private static final long serialVersionUID = -9127358545321739523L;
private int id;
private String addressLine1;
private String city;
private String state;
private int zipCode;
private person person;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getZipCode() {
return zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
public person getPerson() {
return person;
}
public void setPerson(person person) {
this.person = person;
}
}
hibernate.cfg.xml
<!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">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">oracle123</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping resource="person.hbm.xml"/> <mapping resource="personaddress.hbm.xml"/>
</session-factory>
</hibernate-configuration>
person.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping >
<class name="person" table="persons_o">
<id name="id" column="P_ID" type="integer">
<generator class="increment" />
</id>
<property name="name" column="NAME" update="false"
type="string" />
<property name="age" column="AGE" type="integer" />
<one-to-one name="address" cascade="all"></one-to-one>
</class>
</hibernate-mapping>
personaddress.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="personaddress" table="address_o"
dynamic-insert="true" dynamic-update="true"
select-before-update="false">
<id name="id" column="A_ID" type="integer">
<generator class="increment" />
</id>
<property name="addressLine1" column="ADDRESS_LINE_1"
type="string" />
<property name="city" column="CITY" type="string" />
<property name="state" column="STATE" type="string" />
<property name="zipCode" column="ZIPCODE" type="integer" />
<!-- In One-to-one we cannot specify the foreign key column
that has to be filled up
<one-to-one name="person" class="PersonOTO_B" cascade="all"
constrained="true"> </one-to-one>
-->
<many-to-one name="person" column="P_ID" unique="true"
not-null="true" lazy="false" />
</class>
</hibernate-mapping>
My output is :
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Hibernate: select max(P_ID) from persons_o
Primary Key : 1
---going for sleep--- (i am checking my db at this point but no data found )
Hibernate: select max(A_ID) from address_o
Primary Key again : 1
Hibernate: insert into persons_o (NAME, AGE, P_ID) values (?, ?, ?)
Hibernate: insert into address_o (ADDRESS_LINE_1, CITY, STATE, ZIPCODE, P_ID, A_ID) values (?, ?, ?, ?, ?, ?)
Please correct my knowledge.
Thanks
Jayendra Bhatt

session.save(Object), sesson.saveOrUpdate(Object) and etc. method only converts any transient object into persistence object,
means object associates with current hibernate session(actually object associates with session functional queues e.g. insertion queue,
updation queue and etc. according to corresponding operation) and gets hibernate generated(provided by generator class) id
if it's a new object. it never means that object will be immediately mapped on database.
When current hibernate session flushes or hibernate transaction commits then only actual query runs to map object data
into the database.

Related

java.sql.SQLException: ResultSet may only be accessed in a forward direction

I have a program that works smoothly on MySQL database. Now for external requirements, I must switch to SQL Server. Thanks to Hibernate the switch was smooth, except for the error:
java.sql.SQLException: ResultSet may only be accessed in a forward direction.
I am getting this error when performing a custom pagination on the data that I get from the database. Below is a minimal example that tries to get and paginate the users stored in the database (the following example assumes that there are at least 3 rows in the table).
Custom pagination:
import org.hibernate.Query;
import org.hibernate.Session;
public class newMain1 {
public static void main(String[] args) {
getList(1, getSession());
getList(2, getSession());
}
private static void getList(int page, Session s) {
int rowsPerPage = 2;
String hql = "FROM User u ";
try {
Query query = s.createQuery(hql);
int start = (page - 1) * rowsPerPage;
query.setFirstResult(start);
query.setMaxResults(rowsPerPage);
//line that throws exception when int page is 2
query.list();
//line that throws exception when int page is 2
} finally {
if (s.isOpen()) {
s.close();
}
}
}
private Session getSession(){
//gets org.hibernate.Session
}
}
User Java POJO:
public class User {
private Long id;
private String username;
private String password;
private String email;
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
User table for SQL Server:
CREATE TABLE [USER] (
ID bigint NOT NULL,
USERNAME varchar(150) NOT NULL UNIQUE,
PASSWORD varchar(150) NOT NULL,
EMAIL varchar(150) NOT NULL UNIQUE,
PRIMARY KEY (ID)
);
Hibernate mapping of User POJO:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="product.model.User" table="USER">
<id column="ID" name="id" type="long">
<generator class="increment"/>
</id>
<property column="EMAIL" name="email" type="string"/>
<property column="USERNAME" name="username" type="string"/>
<property column="PASSWORD" name="password" type="string"/>
</class>
</hibernate-mapping>
Hibernate cfg xml:
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:jtds:sqlserver://127.0.0.1:1433;DatabaseName=myDB;prepareSQL=3;sendStringParametersAsUnicode=false;</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">myPassword</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.globally_quoted_identifiers">true</property>
<mapping resource="product_mapping/user.hbm.xml"/>
</session-factory>
I am using SQL Server 2012, JDK 1.8, Hibernate 4.0.1.Final, jtds driver 1.3.1
Please note that getList(1, getSession()) will not throw the exception, whereas getList(2, getSession()) will.
After hours of investigation i have find out that this problem was due to the hibernate dialect that i was using.
The correct dialect, considering the hibernate version i am required to use, is: org.hibernate.dialect.SQLServer2008Dialect
Source: https://forum.hibernate.org/viewtopic.php?p=2452163

Could not determine type for: String, at table: STUDENT, for columns: [org.hibernate.mapping.Column(SNAME)]

how to resolve this exception... please help me...
while I am executing this simple hibernate programme. I am getting this exception :
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: String, at table: STUDENT, for columns: [org.hibernate.mapping.Column(SNAME)]
mapping file:
<?xml version = "1.0" encoding = "utf-8"?>
<hibernate-mapping>
<class name = "Student" table = "STUDENT" >
<meta attribute="Class description">
This contains Student details.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="name" column="SNAME" type="String"/>
<property name="mNo" column="MNO" type="String"/>
<property name="marks" column="MARKS" type="String"/>
</class>
configuration file:
<?xml version = "1.0" encoding = "utf-8"?>
<hibernate-configuration>
<session-factory>
<!-- <property name="hibernate.dialect">org.hibernate.dialect.MySQLdialect</property> -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/firsthibernate</property>
<property name="hibernate.connection.user">root</property>
<property name="hibernate.connection.password">asdf</property>
<mapping resource="Student.hbm.xml"/>
</session-factory>
Pojo class:
public class Student {
private int id;
private String name;
private String mNo;
private String marks;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getmNo() {
return mNo;
}
public void setmNo(String mNo) {
this.mNo = mNo;
}
public String getMarks() {
return marks;
}
public void setMarks(String marks) {
marks = marks;
}
}
Test class:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class DemoStudent {
public static void main(String[] args) {
Student st=new Student();
st.setId(1);
st.setName("Amit");
st.setmNo("8927070972");
st.setMarks("98%");
Configuration cfg=new Configuration();
cfg.configure();
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction tr=s.beginTransaction();
tr.begin();
s.save(st);
tr.commit();
}
}
Thanks in advance... while I am executing this simple hibernate programme. I am getting this please help me where I am doing mistake in this programme.
In hibernate mapping file use type as string instead of String.
<property name="name" column="SNAME"
type="string"/>

child collection is not updating in hibernate with cascade all?

I have two tables - Student and Address. They have one to many relationship. Student entity is having collection of address entity. When i updating collection of address in student. Its not updating the data and giving this error. When i was updating the parent entity with child collection, its taking next to be incremented key which is not in the database. -
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:124)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:189)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:59)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3079)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3521)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:395)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:387)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:303)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:349)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1195)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at com.HibernateExample.test.HibernateTest.main(HibernateTest.java:51)
Caused by: org.postgresql.util.PSQLException: ERROR: insert or update on table "address" violates foreign key constraint "student_fk"
Detail: Key (id)=(5) is not present in table "student".
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2476)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2189)
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:186)
... 14 more
Student.java
public class Student {
public int id;
public String firstName;
public String lastName;
public int age;
public Set<Address> address = new HashSet<>(0);
public Set<Address> getAddress() {
return address;
}
public void setAddress(Set<Address> address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Address.java
public class Address {
public int id;
public String streetName;
public String cityName;
public String stateName;
public String plotNo;
public Student student;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public String getPlotNo() {
return plotNo;
}
public void setPlotNo(String plotNo) {
this.plotNo = plotNo;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
HibernateTest.java
public class HibernateTest {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure("hibernate-cfg.xml");
#SuppressWarnings("deprecation")
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.COMMIT);
System.out.println(session.getFlushMode().name());
Transaction transaction = session.beginTransaction();
Student student = (Student) session.get(Student.class, 3);
Address address = new Address();
address.setStateName("Kerala");
address.setCityName("Old Delhi");
address.setStreetName("Uttaam Nagar");
address.setPlotNo("158A");
address.setStudent(student);
student.getAddress().add(address);
session.update(student);
transaction.commit();
session.close();
sessionFactory.close();
}
}
address.hbm.xml
<hibernate-mapping>
<class name="com.HibernateExample.entity.Address" table="address">
<meta attribute="class-description">
This class contains the address detail.
</meta>
<id name="id" type="int" column="id">
<generator class="increment" />
</id>
<property name="streetName" column="street_name" type="string"/>
<property name="cityName" column="city_name" type="string"/>
<property name="stateName" column="state_name" type="string"/>
<property name="plotNo" column="plot_no" type="string"/>
<many-to-one name="student" class="com.HibernateExample.entity.Student" >
<column name="student_id" not-null="true"></column>
</many-to-one>
</class>
</hibernate-mapping>
student.hbm.xml
<hibernate-mapping>
<class name="com.HibernateExample.entity.Student" table="student">
<meta attribute="class-description">
This class contains the student detail.
</meta>
<id name="id" type="int" column="id">
<generator class="increment" />
</id>
<property name="firstName" column="first_name" type="string" length="40" />
<property name="lastName" column="last_name" type="string" length="40" />
<property name="age" column="age" type="int"/>
<set name="address" cascade="all">
<key column="student_id"/>
<one-to-many class="com.HibernateExample.entity.Address"/>
</set>
</class>
</hibernate-mapping>
From the Session javadoc, Session.update() is specified to work with a detached entity instance. "If there is a persistent instance with the same identifier, an exception is thrown." Exactly which exception is not specified, and cascading might send it down a complex code path, which could result in this error.
The Student object you modify is not detached, but rather persistent, because you got it by loading from the Session and have not closed the Session or done anything else that would detach it. This means that all modifications to it are saved to the database automatically, with no need for any manual call on Session. This is specified in the class javadoc for Session, with the sentence "Changes to persistent instances are detected at flush time and also result in an SQL UPDATE."
Simply delete the line session.update(student);, and I think your code will start working, including saving the new address through the cascaded relationship when you commit the transaction.
It's been a while since I've worked with cascades so I'm not entirely certain, but you might also need to set cascade on the other side of the relationship.
The "student_id" is not associated with any of your primary keys. If "student_id" exists in both Student and Address tables then change this line in your student mapping file from "id" to "student_id":
<id name="id" type="int" column="student_id">
Double check your database table with a database table viewer/browser.
It seems you try to insert an ID that already exists in the database (5)

Exception in thread "main" org.hibernate.MappingException: Unknown entity: org.hibernate.employee

Not sure what is wrong. I am getting the exception given:
org.hibernate.MappingException: Unknown entity: org.hibernate.employee
How to fix it? I created client.java. I created the table that mapped that matched the client. I have created the mapping and added the mapping
hibernateutil.java coding
package org.hibernate.test.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class hibernateutil {
private static SessionFactory sessionfactory;
public static SessionFactory getSessionFactory(){
if(sessionfactory == null){
synchronized(hibernateutil.class){
if(sessionfactory == null){
try {
Configuration conf=new Configuration().configure();
StandardServiceRegistryBuilder builder= new StandardServiceRegistryBuilder()
.applySettings(conf.getProperties());
sessionfactory = conf.buildSessionFactory(builder.build());
}catch (Throwable th){
th.printStackTrace();
throw new ExceptionInInitializerError();
}
}
return sessionfactory;
}
}
else{
return sessionfactory;
}
}
}
employee.java
package org.hibernate;
public class employee {
private int id;
private String firstname;
private String lastname;
private int salary;
public employee(){}
public employee(int id,String firstname,String lastname,int salary)
{
this.id=id;
this.firstname=firstname;
this.lastname=lastname;
this.salary=salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.username">javaguy</property>
<property name="connection.password"></property>
<property name="hibernate.jdbc.batch_size">100</property>
<property name="connection.pool_size">1</property>
<property name="show_sql">false</property>
<property name="format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping resource="org/hibernate/employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Oct 20, 2016 7:56:20 PM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="employee" table="EMPLOYEE">
<id name="id" type="int">
<column name="EMP_ID" />
<generator class="assigned" />
</id>
<property name="firstname" type="java.lang.String">
<column name="FIRST_NAME" />
</property>
<property name="lastname" type="java.lang.String">
<column name="LAST_NAME" />
</property>
<property name="salary" type="int">
<column name="SALARY" />
</property>
</class>
</hibernate-mapping>
client.java
package learn;
import org.hibernate.Session;
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.test.util.hibernateutil;
import org.hibernate.*;
public class client {
private static SessionFactory factory;
public static void main(String[] args) {
factory = hibernateutil.getSessionFactory();
client a = new client();
// Add few employee records in data base
a.addemployee(1,"Sai","Nathan",5000);
a.addemployee(2,"Sai","kumar",6000);
a.addemployee(3,"Santhosh","Kumar",9000);
// List down all employees
/*a.listemployee();
// update employee's record
a.updateemployee(1,20000);
// Delete an employee
a.deleteemployee(3);
// List down all employees
a.listemployee();*/
System.out.println("Finished");
}
/* Method to CREATE an employee in the database */
public Integer addemployee(int id, String fname,String lname,int salary)
{
Session session= factory.openSession();
Transaction tx=session.beginTransaction();
employee e1= new employee(id,fname,lname,salary);
Integer empid=(Integer)session.save(e1);
tx.commit();
session.close();
return empid;
}
/* Method to READ all the employees */
public void listemployee(){
Session session = factory.openSession();
List<employee> emplist = session.createQuery("FROM Employee").list();
for(employee emp:emplist){
System.out.print("First name" +emp.getFirstname());
System.out.print("Last name" +emp.getLastname());
System.out.println("Salary" +emp.getSalary());
}
session.close();
}
/* Method to UPDATE salary for an employee */
public void updateemployee(Integer id,Integer salary)
{
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
employee emp = (employee)session.get(employee.class, id);
emp.setSalary(salary);
session.update(emp);
tx.commit();
session.close();
}
public void deleteemployee(Integer id)
{
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
employee emp = (employee)session.get(employee.class, id);
session.delete(emp);
tx.commit();
}
}
error:
project path:
<class name="employee">
should have full package name (path) and all classes should starts with a capital letter.
So it should be like:
package mypackage;
public class Employee
{
...
}
<class name="mypackage.Employee" ...>

HSQL - HIBERNATE. org.hibernate.HibernateException: identifier of an instance of "....Author.class" was altered from 1 to null

Can't insert data to HSQL DB (in-memory). Please, help me to understand mistake, text from console:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
insert
into
author
(ID, NAME, COUNTRY)
values
(default, ?, ?)
Hibernate:
insert
into
book
(ID, NAME, GENRE, AUTHORID)
values
(default, ?, ?, ?)
Hibernate:
insert
into
book
(ID, NAME, GENRE, AUTHORID)
values
(default, ?, ?, ?)
org.hibernate.HibernateException: identifier of an instance of com.maven.vaadin.bookshelf.Author was altered from 1 to null
at org.hibernate.event.def.DefaultFlushEntityEventListener.checkId(DefaultFlushEntityEventListener.java:85)
at org.hibernate.event.def.DefaultFlushEntityEventListener.getValues(DefaultFlushEntityEventListener.java:190)
at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:147)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:219)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:375)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at com.maven.vaadin.bookshelf.DBManager.save(DBManager.java:50)
at com.maven.vaadin.bookshelf.MyVaadinUI.init(MyVaadinUI.java:43)
at com.vaadin.ui.UI.doInit(UI.java:614)
at com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:223)
at com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:73)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:37)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1371)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:238)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Hibernate:
select
author0_.ID as ID0_,
author0_.NAME as NAME0_,
author0_.COUNTRY as COUNTRY0_
from
author author0_
List size: 0
Hibernate config of connection to DB and links to mapping files
<hibernate-configuration>
<session-factory>
<!-- Database connection settings, Connect to HSQL, IN Memory -->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:mem:test</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property><property name="format_sql">true</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!--create the database schema on startup if required -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/maven/vaadin/bookshelf/Author.hbm.xml"/>
<mapping resource="com/maven/vaadin/bookshelf/Book.hbm.xml"/>
</session-factory>
Hibernate mapping files. First:
<hibernate-mapping package="com.maven.vaadin.bookshelf">
<class name="com.maven.vaadin.bookshelf.Author" table="author">
<id name="id" type="java.lang.Long">
<column name="ID" />
<generator class="native" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="64" not-null="true" unique="true" />
</property>
<property name="country" type="java.lang.String">
<column name="COUNTRY" length="32" not-null="true" />
</property>
<set name="authorbook" table="book" cascade="all" inverse="true">
<key column="AUTHORID" not-null="true" />
<one-to-many class="com.maven.vaadin.bookshelf.Book" />
</set>
</class>
Second:
<hibernate-mapping package="com.maven.vaadin.bookshelf">
<class name="com.maven.vaadin.bookshelf.Book" table="book">
<id name="id" type="java.lang.Long">
<column name="ID" />
<generator class="native" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="32" not-null="true" />
</property>
<property name="genre" type="java.lang.String">
<column name="GENRE" length="32" not-null="true" />
</property>
<many-to-one name="author" class="com.maven.vaadin.bookshelf.Author" not-null="true">
<column name="AUTHORID" />
</many-to-one>
</class>
Javas:
public class Author implements Serializable{
private Long id;
private String name;
private String country;
private Set<Book> authorbook = new HashSet<Book>();
public Author(String name, String country, Set<Book> authorBook){
super();
this.name = name;
this.country = country;
this.authorbook = authorbook;
}
public Author(){}
public void setId(Long Id){this.id = id;}
public Long getId(){return id;}
public void setName(String name){this.name = name;}
public String getName(){return name;}
public void setCountry(String country){this.country = country;}
public String getCountry(){return country;}
public void setAuthorbook(Set<Book> authorBook){this.authorbook = authorBook;}
public Set<Book> getAuthorbook(){return authorbook;}
public void addBook(Book book){
book.setAuthor(this);
this.authorbook.add(book);
}}
public class Book implements Serializable{
private Long id;
private String name;
private String genre;
private Author author;
public Book(String name, String genre){
super();
this.name = name;
this.genre = genre;
}
public Book(){}
public void setId(Long id){this.id = id;}
public Long getId(){return id;}
public void setName(String name){this.name = name;}
public String getName(){return name;}
public void setGenre(String genre){this.genre = genre;}
public String getGenre(){return genre;}
public void setAuthor(Author author){this.author = author;}
public Author getAuthor(){return author;}}
public class DBManager {
public static void main(String[] args){
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
DBManager app = new DBManager();
app.save("Author","Country");
app.list();
}
public void save(String authorName, String authorCountry){
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Long id = null;
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Author author = new Author();
author.setName(authorName);
author.setCountry(authorCountry);
Book bk1 = new Book();
Book bk2 = new Book();
bk1.setName("Book1");;
bk1.setGenre("Genre1");
bk2.setName("Book2");;
bk2.setGenre("Genre2");
author.addBook(bk1);
author.addBook(bk2);
session.save(author);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public void list() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
#SuppressWarnings("unchecked")
List<Author> list = session.createQuery("FROM Author").list();
System.out.println("List size: " + (list).size());
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Author author = (Author) iterator.next();
}
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}}
Problem in your setter method of property id. You passed Id and not id (I is in upper case)-for which hibernate throwing the exception
You should change the setter method parameter name from Id to id, it will work.
public void setId(Long id) {
this.id = id;
}
Even if you changed from this.id = id to this.id = Id it will also work.
public void setId(Long Id) {
this.id = Id;
}

Categories