Hibernate SQLGrammarException: could not prepare statement - java

I have simple project with one class and a corresponding table in the database (MySQL). It works fine if put the hbm2ddl.auto set create in the hibernate configuration file. But, if I take it out. The code throws the following exception:
ERROR: Table "STUDENT" not found; SQL statement:
into student (fname, lname, entrance) values (?, ?, ?) [42102-185]
org.hibernate.exception.SQLGrammarException: could not prepare statement
I have already created the table in database but I don't know why hibernate cannot find the table. I am not sure how the connection to the database works.
<?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.MySQLDialect </property>
<property name="hibernate.CONNECTION.driver_class"> com.mysql.jdbc.Driver </property>
<!-- Assume test is the database name -->
<property name="hibernate.CONNECTION.url">
jdbc:mysql://localhost:3306/sample;MVCC=TRUE;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;SCHEMA=sample
</property>
<property name="hibernate.connection.username"> root </property>
<property name="hibernate.connection.password"> **** </property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- -->
<property name="hbm2ddl.auto">create</property>
<!-- List of XML mapping files -->
<!-- -->
<mapping resource="Student.hbm.xml" />
<!-- <mapping class="ourPackage.Student" /> -->
</session-factory>
</hibernate-configuration>
Student Class:
#Entity
#Table(name="student")
public class Student implements Serializable{
public Student(){
}
public Student(int id, String fName, String lName, String ent){
this.id = id;
this.fname = fName;
this.lname = lName;
this.entrance = ent;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getEntrance() {
return entrance;
}
public void setEntrance(String entrance) {
this.entrance = entrance;
}
#Id
#GeneratedValue
private int id;
private String fname;
private String lname;
private String entrance;
}
Student hibernate config
<hibernate-mapping>
<class name="ourPackage.Student" table="student">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="fname" column="fname" type="string"/>
<property name="lname" column="lname" type="string"/>
<property name="entrance" column="entrance" type="string"/>
</class>
</hibernate-mapping>
Main class
public class StudentDB {
private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;
#SuppressWarnings("deprecation")
public static void main(String[] args) {
try {
// factory = new Configuration().configure().buildSessionFactory();
createSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
StudentDB ME = new StudentDB();
Integer empID1 = ME.addStudent("Alex", "Jason", "2005");
ME.listStudent();
factory.close();
}
public void listStudent() {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query temp = session.createQuery("from Student");
List students = temp.list();
for (Iterator iterator = students.iterator(); iterator.hasNext();) {
Student student = (Student) iterator.next();
System.out.print("First Name: " + student.getFname());
System.out.print(" Last Name: " + student.getLname());
System.out.println(" entrance: " + student.getEntrance());
}
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
return factory;
}
}

Related

MySQL table not mapped by Hibernate 5+

I'm trying to learn Hibernate using MySQL built-in database named world. It has three tables called city, country and countrylanguage. What I'm trying to do is execute SQL statement SELECT * FROM world.city;. When I run my project I'm getting error
org.hibernate.hql.internal.ast.QuerySyntaxException: City is not mapped [from City]
I'm using IntelliJ IDEA and Hibernate 5.2.8.
I created mapping xml file like this:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="pl.hibernatePackage">
<class name="City" table="city">
<id name="id" column="ID" type="int">
<generator class="native"/>
</id>
<property name="name" column="Name" type="string"/>
<property name="countryCode" column="CountryCode" type="string"/>
<property name="district" column="District" type="string"/>
<property name="population" column="Population" type="int"/>
</class>
</hibernate-mapping>
City.java is presented below:
public class City
{
private Integer id;
private String name;
private String countryCode;
private String district;
private Integer population;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public Integer getPopulation() {
return population;
}
public void setPopulation(Integer population) {
this.population = population;
}
}
I'm creating session in HibernateUtil.java
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder();
standardServiceRegistryBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = standardServiceRegistryBuilder.build();
return configuration.buildSessionFactory(serviceRegistry);
}
catch(Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Configuration file
<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/world</property>
<property name="hibernate.connection.username">test</property>
<property name="hibernate.connection.password">1234</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">update</property>
<!-- List of XML mapping files -->
<mapping resource="pl/hibernatePackage/City.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Main
public class Main
{
public static void main(String[] args)
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<City> cities = session.createQuery("from City").list();
for(City c : cities) {
System.out.println(c.getId() + "\t" + c.getName() + "\t" + c.getCountryCode() + "\t" + c.getDistrict() +
"\t" + c.getPopulation());
}
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
}
}
EDIT Full error list
EDIT 2
javac result
I have done some testing and i made it work by using the fully qualified class name:
session.createQuery("from pl.hibernatePackage.City")
Now this is only a workaround without touching your config..
After digging deeper i found out that since hibernate version 5.x, there is a different strategy for building the sessionFactory.
I made your example work by implementing sessionFactory as follows:
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure()
.build();
Metadata metadata = new MetadataSources( standardRegistry )
.getMetadataBuilder()
.build();
return configuration.buildSessionFactory(serviceRegistry);
This is explained with example here: jboss documentation (point 2.4)
Thanks to Maciej's answer and help of other guys I managed to get my example to work by modifying code and cleaning it up a little. I also found out that mapping DB with xml file is outdated so I modifiied properly CityEntity class. Final code:
Main.java
import org.hibernate.Session;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
Session session = HibernateUtil.getSession();
session.beginTransaction();
List<CityEntity> cities = session.createQuery("from CityEntity").list();
for(CityEntity c : cities)
{
System.out.println(c.getId() + "\t" + c.getName() + "\t" + c.getCountryCode() + "\t" + c.getDistrict() +
"\t" + c.getPopulation());
}
session.getTransaction().commit();
HibernateUtil.close();
}
}
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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/world</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- List of mapped classes -->
<mapping class="CityEntity"/>
</session-factory>
</hibernate-configuration>
HibernateUtil.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure()
.build();
return configuration.buildSessionFactory(standardRegistry);
}
catch(Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Session getSession()
{
return sessionFactory.openSession();
}
public static void close()
{
sessionFactory.close();
}
}
CityEntity.java
import javax.persistence.*;
#Entity
#Table(name = "city", schema = "world")
public class CityEntity
{
private int id;
private String name;
private String countryCode;
private String district;
private int population;
#Basic
#Column(name = "CountryCode")
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
#Id
#Column(name = "ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "District")
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
#Basic
#Column(name = "Population")
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
}

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" ...>

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>

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