hibernate doesn't see a setter - java

I am new to hibernate and I have stupid problem. My files:
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.PostgreSQLDialect
</property>
<property name="hibernate.connection.driver_class">
org.postgresql.Driver
</property>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:postgresql://localhost/booktown
</property>
<property name="hibernate.connection.username">
mirek
</property>
<mapping resource="Books.hbm.xml"/>
</session-factory>
</hibernate-configuration>
books.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Books" table="books">
<meta attribute="Książki w booktown">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="title" column="title" type="string"/>
<property name="author_id" column="author_id" type="int"/>
<property name="subject_id" column="subject_id" type="int"/>
</class>
</hibernate-mapping>
Books.java
public class Books
{
private int id;
private String title;
private int author_id;
private int subject_id;
public Books(String title, int author_id, int subject_id)
{
this.title = title;
this.author_id = author_id;
this.subject_id = subject_id;
}
public void setId(int id)
{
this.id = id;
}
public void setTitle(String title)
{
this.title = title;
}
public void setAuthorId(int author_id)
{
this.author_id = author_id;
}
public void setSubjectId(int subject_id)
{
this.subject_id = subject_id;
}
public int getId()
{
return id;
}
public String getTitle()
{
return title;
}
public int getAuthorId()
{
return author_id;
}
public int getSubjectId()
{
return subject_id;
}
}
and Booktown.java
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class Booktown
{
private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;
public static void main(String[] args)
{
try
{
//private static SessionFactory configureSessionFactory() throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
//return factory;
//factory = new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex)
{
System.err.println("Failed to create sessionFactory object." + ex.toString());
throw new ExceptionInInitializerError(ex);
}
Booktown BT = new Booktown();
/* Add few employee records in database */
Integer bID1 = BT.addBook(10, "Jakiś napis", 10, 30);
Integer bID2 = BT.addBook(20, "Jakiś inny napis", 10, 50);
//Integer bID3 = BT.addBook(30, "John", 10000, 14);
/* List down all the employees */
BT.listBooks();
/* Update employee's records */
BT.updateBook(bID1, 5000);
/* Delete an employee from the database */
BT.deleteBook(bID2);
/* List down new list of the employees */
BT.listBooks();
}
/* Method to CREATE a book in the database */
public Integer addBook(int bid, String fname, int lname, int salary)
{
Session session = factory.openSession();
Transaction tx = null;
Integer bID = null;
try
{
tx = session.beginTransaction();
Books book = new Books(fname, lname, salary);
bid = (Integer) session.save(book);
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
return bID;
}
/* Method to READ all the books */
public void listBooks()
{
Session session = factory.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
List<Books> books = session.createQuery("FROM books").list();
for (Iterator<Books> iterator = books.iterator(); iterator.hasNext();)
{
Books book = (Books) iterator.next();
System.out.print("First Name: " + book.getTitle());
System.out.print(" Last Name: " + book.getAuthorId());
System.out.println(" Salary: " + book.getSubjectId());
}
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
}
/* Method to UPDATE author for a book */
public void updateBook(Integer bID, int auth)
{
Session session = factory.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
Books book = (Books) session.get(Books.class, bID);
book.setAuthorId(auth);
session.update(book);
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
}
/* Method to DELETE a book from the records */
public void deleteBook(Integer bID)
{
Session session = factory.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
Books book = (Books) session.get(Books.class, bID);
session.delete(book);
tx.commit();
}
catch (HibernateException e)
{
if (tx != null)
tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
}
}
Code is compiling but at run I get:
> paź 15, 2013 8:44:38 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Failed to create sessionFactory object.org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
Exception in thread "main" java.lang.ExceptionInInitializerError
at Booktown.main(Booktown.java:34)
Caused by: org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:185)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:135)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:385)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1790)
at Booktown.main(Booktown.java:25)
Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:138)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:188)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:341) at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:507)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:146)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:163)
... 4 more
Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:135)
... 13 more
Caused by: org.hibernate.PropertyNotFoundException: Could not find a getter for author_id in class Books
at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:316)
at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:310)
at org.hibernate.mapping.Property.getGetter(Property.java:321)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:444)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:200)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:82)
... 18 more
I found similar problem there was no setter. In my case system says that there is no getter for author_id but it is at line 45 in Books.java.
Could sb tells me what is wrong? Maybe there is an other cause which I don't see...

public int getAuthorId()
{
return author_id;
}
should be (observe, author_id)
public int getAuthor_id()
{
return author_id;
}
OR update XML as #Boris the spider commented.

As far as I know Hibernate requires a no-arg constructor which your Books class does seem to have. So even if you get the save part working I think your code will fail when you attempt to load.
Thus, create a constructor:
public Books(){
}
Why does Hibernate require no argument constructor?
Also, as pointed out previously ditch the XML and use JPA annotations. In line with standard Java conventions rename Books to Book and remove the _ from your variable names.
Alan

I had once this problem and I fix it like that:
You should Generate Constructor, Getters and Setters in NetBeans IDE ( I'm working with IDE is netbeans) so you have to press shortcut ALT+Insert (CTLRL+I on Mac). After invoking the shortcut, all possible generators are offered.

Related

Is it ok to use "<generator class="org.hibernate.id.enhanced.SequenceStyleGenerator">" instead of<generator class="sequence">

Hi Guys i was getting java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist exception while trying to migrate from hibernate3 to hibernate5 i changed my mapping from "generator class="sequence"" to
"generator class="org.hibernate.id.enhanced.SequenceStyleGenerator"
now its working fine.please confirm it that its a legitimate solution.
Thanks
employee hbm
<?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="Employee" table="EMPLOYEE" schema="RPTUSER">
<id name="id" type="int" column="id">
<generator class="org.hibernate.id.enhanced.SequenceStyleGenerator">
<param name="optimizer">none</param>
<param name="sequence_name">testemployee_seq</param>
</generator>
</id>
<property name="firstName" column="first_name" type="string" not-null="true"/>
<property name="lastName" column="last_name" type="string" />
<property name="salary" column="salary" type="int" />
</class>
</hibernate-mapping>
Hibernate-cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//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">
URL</property>
<property name="hibernate.connection.username">USERNAME</property>
<property name="hibernate.connection.password">PASSWORD</property><!-- 3des10qf7 -->
<property name="hibernate.connection.pool_size">1</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<mapping resource="Employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
manage employee class
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Add few employee records in database */
Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 10000);
/* List down all the employees */
ME.listEmployees();
/* Update employee's records */
ME.updateEmployee(empID1, 5000);
/* Delete an employee from the database */
ME.deleteEmployee(empID2);
/* List down new list of the employees */
ME.listEmployees();
}
/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
/* Method to READ all the employees */
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator =
employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to UPDATE salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to DELETE an employee from the records */
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
employee .java
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
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 first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
First of all , I have to thank you for reminding me .
Use <param name="sequence_name">testemployee_seq</param>
Get to the point , maybe you should do like this .
<id name="id">
<generator class="sequence">
<param name="sequence_name">seq_admins</param>
</generator>
</id>

hibernate sorted map mapping? ERROR: HHH000091

Hello all I'm new to Hibernate, and so I'm following some tutorials in the internet. But this example gives me the following error.
Any ideas ??
update 1 -
I tried to fix the bug so many times, but still couldn't do it.
When debugging I found that empID is NULL in addEmployee method.
I think that is the reason for this problem.
Sep 24, 2015 4:20:54 PM
org.hibernate.property.access.spi.SetterMethodImpl set ERROR:
HHH000123: IllegalArgumentException in class: Employee, setter method
of property: certificates Sep 24, 2015 4:20:54 PM
org.hibernate.property.access.spi.SetterMethodImpl set ERROR:
HHH000091: Expected type: java.util.SortedMap, actual value:
org.hibernate.collection.internal.PersistentMap
IllegalArgumentException occurred while calling setter for property
[Employee.certificates (expected type = java.util.SortedMap)]; target
= [Employee#3145028a], property value = [{BusinessManagement=Certificate#18bbd9e6,
ComputerScience=Certificate#54de97b9,
ProjectManagement=Certificate#61bb1e36}] at
org.hibernate.property.access.spi.SetterMethodImpl.set(SetterMethodImpl.java:99)
at
org.hibernate.tuple.entity.AbstractEntityTuplizer.setPropertyValues(AbstractEntityTuplizer.java:607)
at
org.hibernate.tuple.entity.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:220)
at
org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:4510)
at
org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:261)
at
org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:178)
at
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:109)
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:678)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:670) at
org.hibernate.internal.SessionImpl.save(SessionImpl.java:665) at
ManageEmployee.addEmployee(ManageEmployee.java:60) at
ManageEmployee.main(ManageEmployee.java:26) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601) at
com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601) at
org.hibernate.property.access.spi.SetterMethodImpl.set(SetterMethodImpl.java:44)
... 21 more Sep 24, 2015 4:20:54 PM
org.hibernate.property.access.spi.SetterMethodImpl set ERROR:
HHH000123: IllegalArgumentException in class: Employee, setter method
of property: certificates Sep 24, 2015 4:20:54 PM
org.hibernate.property.access.spi.SetterMethodImpl set ERROR:
HHH000091: Expected type: java.util.SortedMap, actual value:
org.hibernate.collection.internal.PersistentMap
IllegalArgumentException occurred while calling setter for property
[Employee.certificates (expected type = java.util.SortedMap)]; target
= [Employee#54b00534], property value = [{BusinessManagement=Certificate#3f7e6be2,
ComputerScience=Certificate#4dce2ff}] at
org.hibernate.property.access.spi.SetterMethodImpl.set(SetterMethodImpl.java:99)
at
org.hibernate.tuple.entity.AbstractEntityTuplizer.setPropertyValues(AbstractEntityTuplizer.java:607)
at
org.hibernate.tuple.entity.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:220)
at
org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:4510)
at
org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:261)
at
org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:178)
at
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:109)
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:678)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:670) at
org.hibernate.internal.SessionImpl.save(SessionImpl.java:665) at
ManageEmployee.addEmployee(ManageEmployee.java:60) at
ManageEmployee.main(ManageEmployee.java:34) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601) at
com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601) at
org.hibernate.property.access.spi.SetterMethodImpl.set(SetterMethodImpl.java:44)
... 21 more Sep 24, 2015 4:20:54 PM
org.hibernate.hql.internal.QueryTranslatorFactoryInitiator
initiateService INFO: HHH000397: Using ASTQueryTranslatorFactory
Exception in thread "main" java.lang.IllegalArgumentException: id to
load is required for loading at
org.hibernate.event.spi.LoadEvent.(LoadEvent.java:92) at
org.hibernate.event.spi.LoadEvent.(LoadEvent.java:62) at
org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2624)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:955) at
ManageEmployee.updateEmployee(ManageEmployee.java:106) at
ManageEmployee.main(ManageEmployee.java:40) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601) at
com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
RDBMS tables
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
create table CERTIFICATE (
id INT NOT NULL auto_increment,
certificate_type VARCHAR(40) default NULL,
certificate_name VARCHAR(30) default NULL,
employee_id INT default NULL,
PRIMARY KEY (id)
);
POJO Classes
import java.util.*;
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
private SortedMap certificates;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
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 first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
public SortedMap getCertificates() {
return certificates;
}
public void setCertificates( SortedMap certificates ) {
this.certificates = certificates;
}
}
Comparator
import java.util.Comparator;
public class MyClass implements Comparator <String>{
public int compare(String o1, String o2) {
final int BEFORE = -1;
final int AFTER = 1;
/* To reverse the sorting order, multiple by -1 */
if (o2 == null) {
return BEFORE * -1;
}
Comparable thisCertificate = o1;
Comparable thatCertificate = o2;
if(thisCertificate == null) {
return AFTER * 1;
} else if(thatCertificate == null) {
return BEFORE * -1;
} else {
return thisCertificate.compareTo(thatCertificate) * -1;
}
}
}
Certificate Class
public class Certificate implements Comparable <String>{
private int id;
private String name;
public Certificate() {}
public Certificate(String name) {
this.name = name;
}
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 compareTo(String that){
final int BEFORE = -1;
final int AFTER = 1;
if (that == null) {
return BEFORE;
}
Comparable thisCertificate = this;
Comparable thatCertificate = that;
if(thisCertificate == null) {
return AFTER;
} else if(thatCertificate == null) {
return BEFORE;
} else {
return thisCertificate.compareTo(thatCertificate);
}
}
}
Hibernate Mapping File
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<map name="certificates" cascade="all" sort="MyClass">
<key column="employee_id"/>
<index column="certificate_type" type="string"/>
<one-to-many class="Certificate"/>
</map>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
<class name="Certificate" table="CERTIFICATE">
<meta attribute="class-description">
This class contains the certificate records.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="name" column="certificate_name" type="string"/>
</class>
</hibernate-mapping>
Application Class
import java.util.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Let us have a set of certificates for the first employee */
TreeMap set1 = new TreeMap();
set1.put("ComputerScience", new Certificate("MCA"));
set1.put("BusinessManagement", new Certificate("MBA"));
set1.put("ProjectManagement", new Certificate("PMP"));
/* Add employee records in the database */
Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1);
/* Another set of certificates for the second employee */
TreeMap set2 = new TreeMap();
set2.put("ComputerScience", new Certificate("MCA"));
set2.put("BusinessManagement", new Certificate("MBA"));
/* Add another employee record in the database */
Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, set2);
/* List down all the employees */
ME.listEmployees();
/* Update employee's salary records */
ME.updateEmployee(empID1, 5000);
/* Delete an employee from the database */
ME.deleteEmployee(empID2);
/* List down all the employees */
ME.listEmployees();
}
/* Method to add an employee record in the database */
public Integer addEmployee(String fname, String lname,
int salary, TreeMap cert){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employee.setCertificates(cert);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
/* Method to list all the employees detail */
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator1 =
employees.iterator(); iterator1.hasNext();){
Employee employee = (Employee) iterator1.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
SortedMap<String, Certificate> map =
employee.getCertificates();
for(Map.Entry<String,Certificate> entry : map.entrySet()){
System.out.print("\tCertificate Type: " + entry.getKey());
System.out.println(", Name: " +
(entry.getValue()).getName());
}
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to update salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to delete an employee from the records */
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
It was a problem regarding Hibernate version. You should always make sure that you have taken the correct version of the package.
For this example it should be Hibernate 3x.

Session.get throwing exception instead of null

I run below program and expect that hibernate will throw ObjectNotFoundException for call to load and null for call to get. But I don't see book : null in the output.
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class LoadAndGetTest {
public static void main(String[] args) {
Configuration configuration = new Configuration().configure();
SessionFactory factory = configuration.buildSessionFactory();
Session session = factory.openSession();
try {
Book book = (Book) session.load(Book.class, "DOES_NOT_EXIST");
} catch(Exception exception) {
exception.printStackTrace();
}
Book book = (Book) session.get(Book.class, "DOES_NOT_EXIST");
System.out.println("book : "+ book);
}
}
Book.java
import java.util.Date;
import java.util.List;
public class Book {
private String isbn;
private String name;
private Publisher publisher;
private Date publishDate;
private int price;
private List chapters;
// Getters and Setters
public Book() {
}
public Book(String isbn, String name, Publisher publisher,
Date publishDate, int price, List chapters) {
super();
this.isbn = isbn;
this.name = name;
this.publisher = publisher;
this.publishDate = publishDate;
this.price = price;
this.chapters = chapters;
}
public String getIsbn() {
return isbn;
}
public String getName() {
return name;
}
public Publisher getPublisher() {
return publisher;
}
public Date getPublishDate() {
return publishDate;
}
public int getPrice() {
return price;
}
public List getChapters() {
return chapters;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public void setName(String name) {
this.name = name;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
public void setPrice(int price) {
this.price = price;
}
public void setChapters(List chapters) {
this.chapters = chapters;
}
}
and book.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.chatar.hibernate.receipes.example.domain">
<class name="Book" table="BOOK">
<id name="isbn" type="string" column="ISBN" />
<property name="name" type="string" column="BOOK_NAME" />
<property name="publishDate" type="date" column="PUBLISH_DATE" />
<property name="price" type="int" column="PRICE" />
</class>
</hibernate-mapping>
And
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">
org.apache.derby.jdbc.EmbeddedDriver
</property>
<property name="connection.url">jdbc:derby://localhost:1527/BookShopDB</property>
<property name="connection.username">book</property>
<property name="connection.password">book</property>
<property name="dialect">org.hibernate.dialect.DerbyDialect</property>
<mapping resource="com/chatar/hibernate/receipes/example/domain/book.hbm.xml" />
</session-factory>
</hibernate-configuration>
And here's the exception
950 [main] INFO org.hibernate.event.def.DefaultLoadEventListener - Error performing load command
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.chatar.hibernate.receipes.example.domain.Book#DOES_NOT_EXIST]
at org.hibernate.impl.SessionFactoryImpl$2.handleEntityNotFound(SessionFactoryImpl.java:449)
at org.hibernate.event.def.DefaultLoadEventListener.returnNarrowedProxy(DefaultLoadEventListener.java:320)
at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:277)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:152)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1080)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:997)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:990)
at com.chatar.hibernate.receipes.example.LoadAndGetTest.main(LoadAndGetTest.java:21)
Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.chatar.hibernate.receipes.example.domain.Book#DOES_NOT_EXIST]
at org.hibernate.impl.SessionFactoryImpl$2.handleEntityNotFound(SessionFactoryImpl.java:449)
at org.hibernate.event.def.DefaultLoadEventListener.returnNarrowedProxy(DefaultLoadEventListener.java:320)
at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:277)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:152)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1080)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:997)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:990)
at com.chatar.hibernate.receipes.example.LoadAndGetTest.main(LoadAndGetTest.java:21)
However if I remove call to load then I can see book : null in the output.
LoadAndGetTest.java without call to load
public class LoadAndGetTest {
public static void main(String[] args) {
Configuration configuration = new Configuration().configure();
SessionFactory factory = configuration.buildSessionFactory();
Session session = factory.openSession();
Book book = (Book) session.get(Book.class, "DOES_NOT_EXIST");
System.out.println("book : "+ book);
}
}
output
book : null
Also when I called get twice before and after load I can see before one get printed but not the after one.
Here's the LoadAndGetTest again
public class LoadAndGetTest {
public static void main(String[] args) {
Configuration configuration = new Configuration().configure();
SessionFactory factory = configuration.buildSessionFactory();
Session session = factory.openSession();
Book book1 = (Book) session.get(Book.class, "DOES_NOT_EXIST");
System.out.println("book : "+ book1);
try {
Book book = (Book) session.load(Book.class, "DOES_NOT_EXIST");
} catch(Exception exception) {
exception.printStackTrace();
}
Book book = (Book) session.get(Book.class, "DOES_NOT_EXIST");
System.out.println("book : "+ book);
}
}
Output
book : null
1292 [main] INFO org.hibernate.event.def.DefaultLoadEventListener - Error performing load command
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.chatar.hibernate.receipes.example.domain.Book#DOES_NOT_EXIST]
at org.hibernate.impl.SessionFactoryImpl$2.handleEntityNotFound(SessionFactoryImpl.java:449)
at org.hibernate.event.def.DefaultLoadEventListener.returnNarrowedProxy(DefaultLoadEventListener.java:320)
at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:277)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:152)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1080)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:997)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:990)
at com.chatar.hibernate.receipes.example.LoadAndGetTest.main(LoadAndGetTest.java:24)
Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.chatar.hibernate.receipes.example.domain.Book#DOES_NOT_EXIST]
at org.hibernate.impl.SessionFactoryImpl$2.handleEntityNotFound(SessionFactoryImpl.java:449)
at org.hibernate.event.def.DefaultLoadEventListener.returnNarrowedProxy(DefaultLoadEventListener.java:320)
at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:277)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:152)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1080)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:997)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:990)
at com.chatar.hibernate.receipes.example.LoadAndGetTest.main(LoadAndGetTest.java:24)
Ok. I was able to figure out after checking source code and following stack trace:
It seems if you call get after a calling load, Hibernate uses proxy object. Here's the sequence of calls,
1. Book book = (Book) session.get(Book.class, "DOES_NOT_EXIST");
2. SessionImpl.get
public Object get(Class entityClass, Serializable id) throws HibernateException {
return get( entityClass.getName(), id );
}
3. fireLoad(event, LoadEventListener.GET);
4. DefaultLoadEventListener.onLoad
//return a proxy if appropriate
if ( event.getLockMode() == LockMode.NONE ) {
event.setResult( proxyOrLoad(event, persister, keyToLoad, loadType) );
}
5. DefaultLoadEventListener.proxyOrLoad
if ( proxy != null ) {
return returnNarrowedProxy( event, persister, keyToLoad, options, persistenceContext, proxy );
}
6. DefaultLoadEventListener.returnNarrowedProxy
if ( !options.isAllowProxyCreation() ) {
impl = load( event, persister, keyToLoad, options );
if ( impl == null ) {
event.getSession().getFactory().getEntityNotFoundDelegate().handleEntityNotFound( persister.getEntityName(), keyToLoad.getIdentifier());
}
}
7. SessionFactoryImpl.handleEntityNotFound
// EntityNotFoundDelegate
EntityNotFoundDelegate entityNotFoundDelegate = cfg.getEntityNotFoundDelegate();
if ( entityNotFoundDelegate == null ) {
entityNotFoundDelegate = new EntityNotFoundDelegate() {
public void handleEntityNotFound(String entityName, Serializable id) {
throw new ObjectNotFoundException( id, entityName );
}
public boolean isEntityNotFoundException(RuntimeException exception) {
return ObjectNotFoundException.class.isInstance( exception );
}
};
}

Could not parse configuration: /hibernate.cfg.xml in my application

I am trying to do a CRUD operation in hibernate. i have written the following steps for my application.
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.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/hibernate
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<property name="connection.pool_size">1</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create-drop</property>
<mapping resource="Employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
This is my 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">
<hibernate-mapping>
<class name="com.bullraider.crud.Employee" table="emp1000">
<meta attribute="class-description"> This class contains employee details. </meta>
<id name="empno" type="long" column="empno">
<generator class="native" />
</id>
<property name="ename" type="string" column="ename" not-null="true" />
<property name="job" type="string" column="job" not-null="true" />
<property name="sal" type="integer" column="sal" not-null="true" />
<property name="deptno" type="integer" column="deptno"
not-null="true" />
</class>
</hibernate-mapping>
This is my persistance class
public class Employee implements Serializable{
private long empno;
private String ename;
private int sal;
private String job;
private int deptno ;
public long getEmpno() {
return empno;
}
public void setEmpno(long empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
}
This is my util class
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("SessionFactory creation failed" + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
This is driver Class
import java.util.Iterator;
import java.util.List;
import com.bullraider.crud.util.*;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class Main {
public static void main(String[] args) {
Main m = new Main();
m.saveEmployee("Alex", "MANAGER", 50000, 10);
m.saveEmployee("Mike", "CLERK", 1000, 30);
m.saveEmployee("Tom", "SALESMAN", 2000, 10);
// m.retriveEmployee();
// m.deleteEmployee();
// m.updateEmployee();
}
public void saveEmployee(String ename, String job, int sal, int deptno) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Employee emp = new Employee();
emp.setEname(ename);
emp.setJob(job);
emp.setSal(sal);
emp.setDeptno(deptno);
session.save(emp);
transaction.commit();
System.out.println("Records inserted sucessessfully");
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public void retriveEmployee() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
List employee = session.createQuery("from emp1000").list();
for (Iterator iterator = employee.iterator(); iterator.hasNext();) {
Employee employee1 = (Employee) iterator.next();
System.out.println(employee1.getEmpno() + " "
+ employee1.getEname() + " " + employee1.getJob()
+ " " + employee1.getSal() + " "
+ employee1.getDeptno());
}
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public void deleteEmployee() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
String queryString = "from emp1000 where deptno = :deptno";
Query query = session.createQuery(queryString);
query.setInteger("deptno", 30);
Employee employee = (Employee) query.uniqueResult();
session.delete(employee);
System.out.println("One employee is deleted!");
// Another way to write it
/*
* String hql = "delete from Employee insurance where deptno = 30";
* Query query1 = session.createQuery(hql); int row =
* query1.executeUpdate(); if (row == 0){
* System.out.println("Doesn't deleted any row!"); } else{
* System.out.println("Deleted Row: " + row); }
*/
System.out.println("One employee is deleted!");
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public void updateEmployee() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
String queryString = "from emp1000 where sal = :sal";
Query query = session.createQuery(queryString);
query.setInteger("sal", 8000);
Employee employee = (Employee) query.uniqueResult();
employee.setSal(11000);
session.update(employee);
System.out.println("One employee is updated!");
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}

Hibernate program errors

I am following this tutorial using eclipse EE : hibernate-tutorial-for-begin. There are the errors I am getting. One more thing is that I couldn't find all mentioned jar files in any one hibernate distribution, so I have all jars from openlogic-hibernate-3.3.1.GA-all-bin-1 & lib/jpa from hibernate-release-4.0.0.CR5 bec it was not included in 3.3.1.
I made tables in MySql.
EDIT
Here is list of Jar files I am using:
lib\mysql-connector-java-5.1.18-bin.jar
lib\slf4j-simple-1.6.4.jar
lib\antlr-2.7.6.jar
lib\commons-collections-3.1.jar
lib\dom4j-1.6.1.jar
lib\hibernate3.jar
lib\hibernate-cglib-repack-2.1_3.jar
lib\hibernate-entitymanager-4.0.0.CR5.jar
lib\javassist-3.4.GA.jar
lib\jta-1.1.jar
lib\slf4j-api-1.5.2.jar
Here are the errors:
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
at com.hib.HibernateUtil.<clinit>(HibernateUtil.java:7)
at com.hib.Test.addUser(Test.java:61)
at com.hib.Test.main(Test.java:20)
Caused by: java.lang.IllegalAccessError: tried to access field org.slf4j.impl.StaticLoggerBinder.SINGLETON from class org.slf4j.LoggerFactory
at org.slf4j.LoggerFactory.<clinit>(LoggerFactory.java:60)
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:151)
at com.hib.HibernateUtil.buildSessionFactory(HibernateUtil.java:11)
... 3 more
Here are program files:
Test.Java
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
Test tst = new Test();
/**
* adding records
*/
tst.addUser("Saranga", "Rath");
tst.addUser("Isuru", "Sampath");
tst.addUser("Saranga", "Jaya");
tst.addUser("Prasanna", "Milinda");
tst.addTask(1, "Call", "Call Pubudu at 5 PM");
tst.addTask(1, "Shopping", "Buy some foods for Kity");
tst.addTask(2, "Email", "Send birthday wish to Pubudu");
tst.addTask(2, "SMS", "Send message to Dad");
tst.addTask(2, "Office", "Give a call to Boss");
/**
* retrieving data
*/
tst.getFullName("Saranga");
/**
* full updating records
*/
User user = new User();
user.setId(1);
user.setFirstName("Saranga");
user.setLastName("Rathnayake");
tst.updateUser(user);
/**
* partial updating records
*/
tst.updateLastName(3, "Jayamaha");
/**
* deleting records
*/
User user1 = new User();
user1.setId(4);
tst.deleteUser(user1);
}
private void addUser(String firstName, String lastName) {
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
User user = new User();
user.setFirstName(firstName);
user.setLastName(lastName);
session.save(user);
session.getTransaction().commit();
} catch (RuntimeException e) {
if(trns != null){
trns.rollback();
}
e.printStackTrace();
} finally{
session.flush();
session.close();
}
}
private void addTask(int userID, String title, String description) {
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
Task task = new Task();
task.setUserID(userID);
task.setTitle(title);
task.setDescription(description);
session.save(task);
session.getTransaction().commit();
} catch (RuntimeException e) {
if(trns != null){
trns.rollback();
}
e.printStackTrace();
} finally{
session.flush();
session.close();
}
}
private void updateLastName(int id, String lastName) {
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
String hqlUpdate = "update User u set u.lastName = :newLastName where u.id = :oldId";
int updatedEntities = session.createQuery( hqlUpdate )
.setString( "newLastName", lastName )
.setInteger( "oldId", id )
.executeUpdate();
trns.commit();
} catch (RuntimeException e) {
if(trns != null){
trns.rollback();
}
e.printStackTrace();
} finally{
session.flush();
session.close();
}
}
private void updateUser(User user) {
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
session.update(user);
session.getTransaction().commit();
} catch (RuntimeException e) {
if(trns != null){
trns.rollback();
}
e.printStackTrace();
} finally{
session.flush();
session.close();
}
}
private void getFullName(String firstName) {
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
List<User> users = session.createQuery("from User as u where u.firstName = :firstName")
.setString( "firstName", firstName )
.list();
for (Iterator<User> iter = users.iterator(); iter.hasNext();) {
User user = iter.next();
System.out.println(user.getFirstName() +" " + user.getLastName());
}
trns.commit();
} catch (RuntimeException e) {
if(trns != null){
trns.rollback();
}
e.printStackTrace();
} finally{
session.flush();
session.close();
}
}
private void deleteUser(User user) {
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
session.delete(user);
session.getTransaction().commit();
} catch (RuntimeException e) {
if(trns != null){
trns.rollback();
}
e.printStackTrace();
} finally{
session.flush();
session.close();
}
}
}
HibernateUtil.java
package com.hib;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/userdata</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="user.hbm.xml"/>
<mapping resource="task.hbm.xml"/>
</session-factory>
</hibernate-configuration>
task.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="com.hib.Task" table="tasks">
<id name="id" type="int" column="id" >
<generator class="native"/>
</id>
<property name="userID">
<column name="user_id" />
</property>
<property name="title">
<column name="title" />
</property>
<property name="description">
<column name="description"/>
</property>
</class>
</hibernate-mapping>
user.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="com.hib.User" table="users" >
<id name="id" type="int" column="id" >
<generator class="native"/>
</id>
<property name="firstName">
<column name="first_name" />
</property>
<property name="lastName">
<column name="last_name"/>
</property>
</class>
</hibernate-mapping>
Task Class
package com.hib;
public class Task {
private Integer id;
private Integer userID;
private String title;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserID() {
return userID;
}
public void setUserID(Integer userID) {
this.userID = userID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
User Class
package com.hib;
public class User {
private Integer id;
private String firstName;
private String lastName;
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
}
The runtime exception you've got is caused by slf4j (logging framework used by Hibernate). Make sure that you have provided the correct implementation that matches the slf4j API Hibernate was compiled with in your classpath, e.g. for Hibernate 3.3.1 (according to pom) the correct version is 1.5.2 (choose the target logging mechanism, e.g. simple/log4j/jdk14, according to your environment).
It's not compile-time error, it's run-time. You are missing slf4j-log4j12.jar binding or other, depending on what underlying logging framework you want to use.
You can download it from http://www.slf4j.org/
try to add hibernate-jpa-xxx.jar into your classpath.
Verify the database connection configuration as well.

Categories