/* EMPLOYEE table */
CREATE TABLE `employee` (
 `employee_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
 `firstname` VARCHAR(50) NULL DEFAULT NULL,
 `lastname` VARCHAR(50) NULL DEFAULT NULL,
 `birth_date` DATE NOT NULL,
 `cell_phone` VARCHAR(15) NOT NULL,
 PRIMARY KEY (`employee_id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=216
/* EMPLOYEEDETAIL table */
CREATE TABLE `employeedetail` (
 `employee_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
 `street` VARCHAR(50) NULL DEFAULT NULL,
 `city` VARCHAR(50) NULL DEFAULT NULL,
 `state` VARCHAR(50) NULL DEFAULT NULL,
 `country` VARCHAR(50) NULL DEFAULT NULL,
 PRIMARY KEY (`employee_id`),
 CONSTRAINT `FKEMPL` FOREIGN KEY (`employee_id`) REFERENCES `employee` (`employee_id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=216
Code language: SQL (Structured Query Language) (sql)<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>net.viralpatel.hibernate</groupId>
 <artifactId>HibernateHelloWorldXML</artifactId>
 <packaging>jar</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>HibernateHelloWorldXML</name>
 <url>http://maven.apache.org</url>
 <dependencies>
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.10</version>
  </dependency>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate</artifactId>
   <version>3.2.6.ga</version>
  </dependency>
 </dependencies>
</project>
Code language: HTML, XML (xml)package net.viralpatel.hibernate;
import java.sql.Date;
public class Employee {
 private Long employeeId;
 private String firstname;
 private String lastname;
 private Date birthDate;
 private String cellphone;
 private EmployeeDetail employeeDetail;
 public Employee() {
 }
 public Employee(String firstname, String lastname, Date birthdate,
   String phone) {
  this.firstname = firstname;
  this.lastname = lastname;
  this.birthDate = birthdate;
  this.cellphone = phone;
 }
 // Getter and Setter methods 
}
Code language: Java (java)package net.viralpatel.hibernate;
public class EmployeeDetail {
 private Long employeeId;
 private String street;
 private String city;
 private String state;
 private String country;
 private Employee employee;
 public EmployeeDetail() {
 }
 public EmployeeDetail(String street, String city, String state, String country) {
  this.street = street;
  this.city = city;
  this.state = state;
  this.country = country;
 }
 
 // Getter and Setter methods 
}
Code language: Java (java)Employee.hbm.xml and EmployeeDetail.hbm.xml for the model classes created in above steps. File: /src/main/java/net/viralpatel/hibernate/Employee.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="net.viralpatel.hibernate">
 <class name="Employee" table="EMPLOYEE">
  <id name="employeeId" column="EMPLOYEE_ID">
   <generator class="native" />
  </id>
  <one-to-one name="employeeDetail" class="net.viralpatel.hibernate.EmployeeDetail"
   cascade="save-update"></one-to-one>
  
  <property name="firstname" />
  <property name="lastname" column="lastname" />
  <property name="birthDate" type="date" column="birth_date" />
  <property name="cellphone" column="cell_phone" />
 </class>
</hibernate-mapping>
Code language: HTML, XML (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="net.viralpatel.hibernate">
    <class name="EmployeeDetail" table="EMPLOYEEDETAIL">
   <id name="employeeId" type="java.lang.Long">
   <column name="EMPLOYEE_ID" />
   <generator class="foreign">
    <param name="property">employee</param>
   </generator>
  </id>
  <one-to-one name="employee" class="net.viralpatel.hibernate.Employee"
   constrained="true"></one-to-one>
  
        <property name="street" column="STREET"/>
        <property name="city" column="CITY"/>
        <property name="state" column="STATE"/>
        <property name="country" column="COUNTRY"/>
 </class>
</hibernate-mapping>
Code language: HTML, XML (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">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/tutorial</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>
        
        <property name="connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">validate</property>
 
        <mapping resource="net/viralpatel/hibernate/EmployeeDetail.hbm.xml"/>
        <mapping resource="net/viralpatel/hibernate/Employee.hbm.xml"/>
    
    </session-factory>
</hibernate-configuration>
Code language: HTML, XML (xml)package net.viralpatel.hibernate;
 
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) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
Code language: Java (java)package net.viralpatel.hibernate;
import java.sql.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class Main {
 public static void main(String[] args) {
  SessionFactory sf = HibernateUtil.getSessionFactory();
  Session session = sf.openSession();
  session.beginTransaction();
  EmployeeDetail employeeDetail = new EmployeeDetail("10th Street", "LA", "San Francisco", "U.S.");
  
  Employee employee = new Employee("Nina", "Mayers", new Date(121212),
    "114-857-965");
  employee.setEmployeeDetail(employeeDetail);
  employeeDetail.setEmployee(employee);
  
  
  session.save(employee);
  
  List<Employee> employees = session.createQuery("from Employee").list();
  for (Employee employee1 : employees) {
   System.out.println(employee1.getFirstname() + " , "
     + employee1.getLastname() + ", "
     + employee1.getEmployeeDetail().getState());
  }
  session.getTransaction().commit();
  session.close();
 }
}
Code language: Java (java)Code language: HTML, XML (xml)Hibernate: insert into EMPLOYEE (firstname, lastname, birth_date, cell_phone) values (?, ?, ?, ?) Hibernate: insert into EMPLOYEEDETAIL (STREET, CITY, STATE, COUNTRY, EMPLOYEE_ID) values (?, ?, ?, ?, ?) Hibernate: select employee0_.EMPLOYEE_ID as EMPLOYEE1_1_, employee0_.firstname as firstname1_, employee0_.lastname as lastname1_, employee0_.birth_date as birth4_1_, employee0_.cell_phone as cell5_1_ from EMPLOYEE employee0_ Hibernate: select employeede0_.EMPLOYEE_ID as EMPLOYEE1_0_0_, employeede0_.STREET as STREET0_0_, employeede0_.CITY as CITY0_0_, employeede0_.STATE as STATE0_0_, employeede0_.COUNTRY as COUNTRY0_0_ from EMPLOYEEDETAIL employeede0_ where employeede0_.EMPLOYEE_ID=? Nina , Mayers, San Francisco
Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
View Comments
Hi Viral,
Its a lovely post and really appriciated your efforts but i have one doubt only, that is, suppose if i want to create a JSP form which contains both the tables details/columns, how can i do that cause In controll class i will create an instance of Employe.java and will declear all the fields on JSP like but how will i declear 'EmployeeDetails' variable on my JSP if i try 'employeeDetails.street' against any then it doesn't identify and gives error.
so in nutshell my requirement is i have form which have all fields exists on employee and employeeDetails table, how will i declear subTable columns on my JSP page ?
Can you/anyone please guide me for this.
Thanks
Hi Tapan,
The EmployeeDetail is part of Employee object. You can simply pass Employee object to JSP and render all attributes as:
[code gutter="false" language="html"]
${employee.firstname}
${employee.lastname}
${employee.employeeDetail.street}
${employee.employeeDetail.city}
[/code]
Hope this works.
Hi,
It's awesome man.
but can you suggest how to read some data from a text file and check whether these values are the same in a table through HIBERNATE XML and annotations too.
Thanks a lot
Hi Ajay,
Your requirement seems to be very specific. All you need to do is to
1) Read a text file in Java using File IO.
2) Iterate through the data in file
3) Use Hibernate to check if data is present by query the db.
Hi , i want to know about
this
employee
What is this pram tag and its "property" attribute
Hi , i want to know about
employee
What is this pram tag and its “property” attribute
employee
What is this param tag and its "property" atribute
Nice Article viral :)
Very helpful
Thanks,
Anil
Thanks A lot man :D
Thanx man. Nice tutorial
Hi James! I’m with you because I just ululsay put my PC into hibernate mode. And although, it’s not difficult to make some few clicks to hibernate a PC, but if there’s an easier way I would appreciate it very much. It’s just through this post that I learned to personalize the power button and I just did it! Thanks to you a lot!
Hi there,
i got an error when i run my test for the second times and it thow me the error: "Oct 25, 2012 3:21:52 PM org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured
org.hibernate.SessionException: Session is closed!
Exception in thread "main" java.lang.NullPointerException
at geomancer.utils.testHibernateConnection.main(testHibernateConnection.java:32)
at org.hibernate.impl.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:49)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1541)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283)
at geomancer.utils.testHibernateConnection.main(testHibernateConnection.java:27)
Java Result: 1
i don't why, but the first times is ok
It's very very helpful tutorial.....................