I am getting the following error while executing a simple hibernate program from the below link
http://www.tutorialspoint.com/hibernate/hibernate_examples.htm
Failed to create sessionFactory object.org.hibernate.MappingException:
Could not read mappings from resource: Employee.hbm.xml Exception in
thread "main" java.lang.ExceptionInInitializerError at
ManageEmployee.main(ManageEmployee.java:21) Caused by:
org.hibernate.MappingException: Could not read mappings from resource:
Employee.hbm.xml at
org.hibernate.cfg.Configuration.addResource(Configuration.java:484)
at
org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1453)
at
org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1421)
at
org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1402)
at
org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1378)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1298)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1284)
at ManageEmployee.main(ManageEmployee.java:18) Caused by:
org.hibernate.MappingException: Could not parse mapping document in
input stream at
org.hibernate.cfg.Configuration.addInputStream(Configuration.java:430)
at
org.hibernate.cfg.Configuration.addResource(Configuration.java:481)
... 7 more Caused by: org.dom4j.DocumentException: www.hibernate.org
Nested exception: www.hibernate.org at
org.dom4j.io.SAXReader.read(SAXReader.java:484) at
org.hibernate.cfg.Configuration.addInputStream(Configuration.java:421)
... 8 more
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;
}
}
ManageEmployee.java
import java.util.List;
import java.util.Date;
import java.util.Iterator;
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();
/* 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.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="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="sequence"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<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 name="sessionFactory">
<!-- Database connection settings -->
<property name="connection.driver_class">com.ibm.db2.jcc.DB2Driver</property>
<property name="connection.url">jdbc:db2://172.18.75.21:60008/tinuat</property>
<!-- <property name="connection.driver_class">net.sf.log4jdbc.DriverSpy</property>
<property name="connection.url">jdbc:log4jdbc:postgresql://172.19.65.152:5432/NIR</property>-->
<property name="connection.username">samol</property>
<property name="connection.password">samolteam</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">30</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.DB2Dialect</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>
<property name="hibernate.connection.release_mode">auto</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">false</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Check your Employee.hbm.xml in correct package in your project and set the class name in bellow xml with correct package name.
<hibernate-mapping>
<class name="yourpackageName.Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="sequence"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
Apparently the Employee.hbm.xml is found but Hiberante can not read the file. Try to replace your file with this code replacing the YOUR PATH HERE (com.something.something) for your real path.
<?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="YOUR PATH HERE (com.something.something)">
<class name="Employee" table="EMPLOYEE" lazy="false">
<id name="id" column="id" type="long">
<generator class="native" />
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="long"/>
</class>
</hibernate-mapping>
Edit class name="your.packageName.Employee" in your Employee.hbm.xml:
<hibernate-mapping>
<class name="your.packageName.Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="sequence"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
Related
how to resolve this exception... please help me...
while I am executing this simple hibernate programme. I am getting this exception :
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: String, at table: STUDENT, for columns: [org.hibernate.mapping.Column(SNAME)]
mapping file:
<?xml version = "1.0" encoding = "utf-8"?>
<hibernate-mapping>
<class name = "Student" table = "STUDENT" >
<meta attribute="Class description">
This contains Student details.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="name" column="SNAME" type="String"/>
<property name="mNo" column="MNO" type="String"/>
<property name="marks" column="MARKS" type="String"/>
</class>
configuration file:
<?xml version = "1.0" encoding = "utf-8"?>
<hibernate-configuration>
<session-factory>
<!-- <property name="hibernate.dialect">org.hibernate.dialect.MySQLdialect</property> -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/firsthibernate</property>
<property name="hibernate.connection.user">root</property>
<property name="hibernate.connection.password">asdf</property>
<mapping resource="Student.hbm.xml"/>
</session-factory>
Pojo class:
public class Student {
private int id;
private String name;
private String mNo;
private String marks;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getmNo() {
return mNo;
}
public void setmNo(String mNo) {
this.mNo = mNo;
}
public String getMarks() {
return marks;
}
public void setMarks(String marks) {
marks = marks;
}
}
Test class:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class DemoStudent {
public static void main(String[] args) {
Student st=new Student();
st.setId(1);
st.setName("Amit");
st.setmNo("8927070972");
st.setMarks("98%");
Configuration cfg=new Configuration();
cfg.configure();
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction tr=s.beginTransaction();
tr.begin();
s.save(st);
tr.commit();
}
}
Thanks in advance... while I am executing this simple hibernate programme. I am getting this please help me where I am doing mistake in this programme.
In hibernate mapping file use type as string instead of String.
<property name="name" column="SNAME"
type="string"/>
when i want to save my object it throws unknown entity exception.
tnx in advance
Exception in thread "main" org.hibernate.MappingException: Unknown
entity: com.simpleProgrammer.User at
org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:618)
at
org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1595)
at
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
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:667)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:659) at
org.hibernate.internal.SessionImpl.save(SessionImpl.java:654) at
com.simpleProgrammer.Program.main(Program.java:22)
my hibernate.cfg.xml file is here
<?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.cj.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/protein_tracker</property>
<property name="hibernate.connection.username">root</property>
<!-- <property name="hibernate.default_schema"></property> -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping resource="com/simpleProgrammer/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
my User.hbm.xml mapping file
<?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">
<hibernate-mapping>
<class name="com.simpleProgrammer.User" table="USERS">
<id name="id" type="int" column="id">
<generator class="identity" />
</id>
<property name="name" column="NAME" type="string" />
<component name="proteinData">
<property name="total" column="TOTAL" type="int" />
<property name="goal" column="GOAL" type="int" />
</component>
<set name="history" table="USER_HISTORY">
<key column="ID"/>
<composite-element class="com.simpleProgrammer.UserHistory">
<property name="entryTime" type="date" column="ENTRY_TIME"/>
<property name="entry" type="string" column="ENTRY"/>
</composite-element>
</set>
</class>
</hibernate-mapping>
my progaram.java
package com.simpleProgrammer;
import java.util.Date;
import org.hibernate.Session;
public class Program {
public static void main(String[] args) {
Session session = new HibernateUtilities().getSessionFactory().openSession();
System.out.println("Session Opened!!!");
session.beginTransaction();
System.out.println("Transaction begined!");
User user = new User();
user.setName("Joe");
user.getHistory().add(new UserHistory(new Date(), "Setting Name to Joe"));
user.getProteinData().setGoal(250);
user.getHistory().add(new UserHistory(new Date(), "Setting Goal to 250!"));
System.out.println("Setting user Object");
session.save(user);
System.out.println("Saving user object on table");
session.getTransaction().commit();
System.out.println("Transaction Commited!");
session.beginTransaction();
User loadedUser = session.get(User.class, 1);
System.out.println(loadedUser.getName());
System.out.println(loadedUser.getProteinData().getGoal());
System.out.println(loadedUser.getProteinData().getTotal());
loadedUser.getProteinData().setTotal(loadedUser.getProteinData().getTotal() + 50);
loadedUser.getHistory().add(new UserHistory(new Date(), "Added 50 Protein!"));
for (UserHistory history : loadedUser.getHistory()) {
System.out.println(history.getEntryTime().toString() + " " + history.getEntry());
}
session.getTransaction().commit();
session.close();
System.out.println("Session Closed!!!");
HibernateUtilities().getSessionFactory().close();
System.out.println("Session Factory Closed");
}
}
user class
package com.simpleProgrammer;
import java.util.HashSet;
import java.util.Set;
public class User {
private int id;
private String name;
private ProteinData proteinData = new ProteinData();
private Set<UserHistory> history = new HashSet<UserHistory>();
public Set<UserHistory> getHistory() {
return history;
}
public void setHistory(Set<UserHistory> history) {
this.history = history;
}
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 ProteinData getProteinData() {
return proteinData;
}
public void setProteinData(ProteinData proteinData) {
this.proteinData = proteinData;
}
}
here is my project structure
I think you should check your other configure file."Unknown entity" means your application doesn't find something like User.hbm.xml in the path.
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" ...>
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;
}
}
As per the document i read here it says :
Hibernate save method returns the generated id immediately, this is possible because primary object is saved as soon as save method is invoked.
But in my example below, i have fired the save method and then kept the thread on sleep for 1 minute.
Within this timespace when i check the database the person_o table doesnt show any data in it. why isnt it showing the age and name value in it immediately after save. though it appears after the commit is executed once sleep is over .
addperson.java:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class addperson {
public static void main(String as[])
{
//Activate Hibernate Software
Configuration cfg=new Configuration();
//make hibernate software locating and reading cfg file
cfg=cfg.configure("/hibernate.cfg.xml");
//create SessionFactory obj
SessionFactory factory=cfg.buildSessionFactory();
//create HB session obj
Session session=factory.openSession();
Transaction tx = session.beginTransaction();
try {
// Create a person
person person = new person();
person.setName("Luna");
person.setAge(33);
Integer key = (Integer) session.save(person);
System.out.println("Primary Key : " + key);
person.setId(key);
System.out.println("---going for sleep---");
Thread.sleep(60000);
// Create the address for the person
personaddress address = new personaddress();
address.setAddressLine1("Lunaris");
address.setCity("Twinkle");
address.setState("MA");
address.setZipCode(10308);
address.setPerson(person);
person.setAddress(address);
key = (Integer) session.save(address);
System.out.println("Primary Key again : " + key);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
session.close();
}
}
}
person.java
import java.io.Serializable;
public class person implements Serializable {
private static final long serialVersionUID = -9127358545321739524L;
private int id;
private String name;
private int age;
private personaddress address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public personaddress getAddress() {
return address;
}
public void setAddress(personaddress address) {
this.address = address;
}
}
personaddress.java
import java.io.Serializable;
public class personaddress implements Serializable {
private static final long serialVersionUID = -9127358545321739523L;
private int id;
private String addressLine1;
private String city;
private String state;
private int zipCode;
private person person;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getZipCode() {
return zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
public person getPerson() {
return person;
}
public void setPerson(person person) {
this.person = person;
}
}
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">oracle123</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping resource="person.hbm.xml"/> <mapping resource="personaddress.hbm.xml"/>
</session-factory>
</hibernate-configuration>
person.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping >
<class name="person" table="persons_o">
<id name="id" column="P_ID" type="integer">
<generator class="increment" />
</id>
<property name="name" column="NAME" update="false"
type="string" />
<property name="age" column="AGE" type="integer" />
<one-to-one name="address" cascade="all"></one-to-one>
</class>
</hibernate-mapping>
personaddress.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="personaddress" table="address_o"
dynamic-insert="true" dynamic-update="true"
select-before-update="false">
<id name="id" column="A_ID" type="integer">
<generator class="increment" />
</id>
<property name="addressLine1" column="ADDRESS_LINE_1"
type="string" />
<property name="city" column="CITY" type="string" />
<property name="state" column="STATE" type="string" />
<property name="zipCode" column="ZIPCODE" type="integer" />
<!-- In One-to-one we cannot specify the foreign key column
that has to be filled up
<one-to-one name="person" class="PersonOTO_B" cascade="all"
constrained="true"> </one-to-one>
-->
<many-to-one name="person" column="P_ID" unique="true"
not-null="true" lazy="false" />
</class>
</hibernate-mapping>
My output is :
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Hibernate: select max(P_ID) from persons_o
Primary Key : 1
---going for sleep--- (i am checking my db at this point but no data found )
Hibernate: select max(A_ID) from address_o
Primary Key again : 1
Hibernate: insert into persons_o (NAME, AGE, P_ID) values (?, ?, ?)
Hibernate: insert into address_o (ADDRESS_LINE_1, CITY, STATE, ZIPCODE, P_ID, A_ID) values (?, ?, ?, ?, ?, ?)
Please correct my knowledge.
Thanks
Jayendra Bhatt
session.save(Object), sesson.saveOrUpdate(Object) and etc. method only converts any transient object into persistence object,
means object associates with current hibernate session(actually object associates with session functional queues e.g. insertion queue,
updation queue and etc. according to corresponding operation) and gets hibernate generated(provided by generator class) id
if it's a new object. it never means that object will be immediately mapped on database.
When current hibernate session flushes or hibernate transaction commits then only actual query runs to map object data
into the database.