Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses
Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

How to persist Java Collections by @ElementCollection annotation in Hibernate using JPA ?

Program demonstrate how to persist Java Collections by @ElementCollection annotation in Hibernate using JPA.





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2



How to use @Transient annotation to make an entity field non-persistent in Hibernate using JPA ?.

Program to demonstrate how to use @Transient annotation to make an entity field non-persistent in Hibernate using JPA.





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2


How to create multiple tables from single entity by @SecondaryTable annotation in Hibernate/JPA ?.

Program to demonstrate how to create multiple tables from single entity by @SecondaryTable annotation in Hibernate/JPA





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2



How to implement Many To Many mapping by @ManyToMany annotation in Hibernate using JPA ?.

Program to demonstrate how to implement Many To Many mapping by @ManyToMany annotation in Hibernate using JPA.





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2


How to implement One To Many mapping by @OneToMany annotation in Hibernate using JPA ?.

Program to demonstrate how to implement One To Many mapping by @OneToMany annotation in Hibernate using JPA





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2


How to implement One To One mapping by @OneToOne annotation in Hibernate using JPA ?.

Program to demonstrate how to implement One To One mapping by @OneToOne annotation in Hibernate using JPA.





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2


How to create Composite Primary Keys by @IdClass annotation in Hibernate using JPA ?

Program to demonstrate how to create Composite Primary Keys by @IdClass annotation in Hibernate using JPA.





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2



How to implement Component Mapping by @Embedded annotation in Hibernate using JPA ?.

Program to demonstrate how to implement Component Mapping by @Embedded annotation in Hibernate using JPA.
 




Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2







How to create persistence xml file in Hibernate using JPA ?.

A simple video explaining persistence.xml file in JPA.
 



How to convert a Java Object into an Entity in Hibernate using JPA ?.

A simple video explaining Entities creation in Hibernate using JPA.
 



How to save collections into database using @ElementCollection, @JoinTable and @JoinColumn annotations in Hibernate Framework ?.

Program to demonstrate how to save collections into database using @ElementCollection, @JoinTable and @JoinColumn annotations in Hibernate Framework.

A simple POJO class (model) Customer.java

package com.hubberspot.hibernate.examples;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;

// @Entity to tell Hibernate that we need this Model
// class to get store in database as a table by name
// Customer
@Entity
public class Customer {

 // @Id to tell Hibernate that we need this Model
 // class having customerId as a Primary Key in the
 // table Customer created by @Entity
 @Id
 private int customerId;
 private String customerName;

 // In order to save collections into database
 // using Hibernate we use an annotation called as
 // @ElementCollection which creates a seperate table
 // for storing the contents of multiple addresses 
 // and associate a foreign key relationship with
 // Customer table.
 @ElementCollection

 // In order to provide user friendly name to the
 // separate table we use @JoinTable annotation which
 // takes in name as the name user wants to provide to 
 // collections table. We can also provide name to foreign key
 // using @JoinColumn annotation
 @JoinTable(name="Customer_Address" , joinColumns=@JoinColumn(name="Customer_Id"))
 private Set< Address >setOfAddresses = new HashSet< Address >();

 public Set< Address >getSetOfAddresses() {
  return setOfAddresses;
 }

 public void setSetOfAddresses(Set< Address >setOfAddresses) {
  this.setOfAddresses = setOfAddresses;
 }
 public int getCustomerId() {
  return customerId;
 }
 public void setCustomerId(int customerId) {
  this.customerId = customerId;
 }

 public String getCustomerName() {
  return customerName;
 }
 public void setCustomerName(String customerName) {
  this.customerName = customerName;
 }
}




A simple POJO class (model) Address which is being used as a collection into Customer

package com.hubberspot.hibernate.examples;

import javax.persistence.Embeddable;

// @Embeddable tells Hibernate that Address object 
// will be embedded into some other tables.
// The values of the properties will be populated
// into a table in which we want to embed the Address
@Embeddable
public class Address {

 private String street;
 private String city;
 private String state;
 private String zipCode;

 public String getStreet() {
  return street;
 }

 public void setStreet(String street) {
  this.street = street;
 }

 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 String getZipCode() {
  return zipCode;
 }

 public void setZipCode(String zipCode) {
  this.zipCode = zipCode;
 } 

}




Hibernate Configuration XML file


<?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/customerdb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">root</property>

 <!-- SQL dialect -->
 <property name="dialect">
  org.hibernate.dialect.MySQL5Dialect
 </property>

 <!-- Drop and re-create the database schema on startup  -->
 <property name="hbm2ddl.auto">create</property>

 <!-- Mapping class entry into configuration xml for annotated classes -->
 <mapping class="com.hubberspot.hibernate.examples.Customer" />

  </session-factory>
</hibernate-configuration>


A simple Test.java

package com.hubberspot.hibernate.examples;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateTest {
 public static void main(String[] args) {

  // Lets create a Customer Object 
  Customer customer = new Customer();
  customer.setCustomerId(1);
  customer.setCustomerName("Jonty");

  // Lets create multiple addresses object which will be
  // saved as a collections into a separate table
  Address address1 = new Address();
  address1.setStreet("Street Name 1");
  address1.setCity("City Name 1");
  address1.setState("State Name 1");
  address1.setZipCode("Zip-Code Value 1");

  Address address2 = new Address();
  address2.setStreet("Street Name 2");
  address2.setCity("City Name 2");
  address2.setState("State Name 2");
  address2.setZipCode("Zip-Code Value 2");

  customer.getSetOfAddresses().add(address1);
  customer.getSetOfAddresses().add(address2);

  // SessionFactory gives us a factory of sessions
  // Usually SessionFactory is been configured by the 
  // configuration file named as hibernate.cfg.xml
  // buildSessionFactory() builds the sessionFactory for us
  SessionFactory sessionFactory = new Configuration().
    configure().buildSessionFactory();

  // Session is created by calling openSession()
  // method on SessionFactory object
  Session session = sessionFactory.openSession();
  session.beginTransaction();

  // Our Transaction Code goes here 
  // i.e save, load , merge and remove
  // Lets save our Customer object created
  // above using sessions save method.
  session.save(customer);

  // Committing the transaction in order to save. 
  session.getTransaction().commit();
  // Closing the session
  session.close();
 }
}




Output of the program : 

Two tables created into database as below: 




 Table 1: Customer












Table 2: Customer_Address


 




Video tutorial to demonstrate how to persist Java Collections by @ElementCollection annotation in Hibernate using JPA.









How to implement @Embeddable and @Embedded annotation in Hibernate Framework ?.

Program to demonstrate how to implement @Embeddable and @Embedded annotation in Hibernate Framework.


A simple POJO class (model) Customer.java

package com.hubberspot.hibernate.examples;

import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;

// @Entity to tell Hibernate that we need this Model
// class to get store in database as a table by name
// Customer
@Entity
public class Customer {

 // @Id to tell Hibernate that we need this Model
 // class having customerId as a Primary Key in the
 // table Customer created by @Entity
 @Id
 private int customerId;
 private String customerName;

 // @Embedded defines that customer address will be
 // embedded by an object called as Address
 // The value of Address will be provided by Address object
 // but in database the properties of Address will be embedded
 // into Customer table.
 @Embedded
 private Address customerAddress;


 public Address getCustomerAddress() {
  return customerAddress;
 }

 public void setCustomerAddress(Address customerAddress) {
  this.customerAddress = customerAddress;
 }
 public int getCustomerId() {
  return customerId;
 }
 public void setCustomerId(int customerId) {
  this.customerId = customerId;
 }

 public String getCustomerName() {
  return customerName;
 }
 public void setCustomerName(String customerName) {
  this.customerName = customerName;
 }
}




A simple POJO class (model) Address which is embedded into Customer

package com.hubberspot.hibernate.examples;

import javax.persistence.Embeddable;

// @Embeddable tells Hibernate that Address object 
// will be embedded into some other tables.
// The values of the properties will be populated
// into a table in which we want to embed the Address
@Embeddable
public class Address {

 private String street;
 private String city;
 private String state;
 private String zipCode;

 public String getStreet() {
  return street;
 }

 public void setStreet(String street) {
  this.street = street;
 }

 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 String getZipCode() {
  return zipCode;
 }

 public void setZipCode(String zipCode) {
  this.zipCode = zipCode;
 } 

}




Hibernate Configuration XML file


<?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/customerdb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">root</property>

 <!-- SQL dialect -->
 <property name="dialect">
  org.hibernate.dialect.MySQL5Dialect
 </property>

 <!-- Drop and re-create the database schema on startup  -->
 <property name="hbm2ddl.auto">create</property>

 <!-- Mapping class entry into configuration xml for annotated classes -->
 <mapping class="com.hubberspot.hibernate.examples.Customer" />

  </session-factory>
</hibernate-configuration>


A simple Test.java
package com.hubberspot.hibernate.examples;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateTest {
 public static void main(String[] args) {

  // Lets create a Customer Object 
  Customer customer = new Customer();
  customer.setCustomerId(1);
  customer.setCustomerName("Jonty");

  // Lets create a Address object which will be
  // embedded into Customer object
  Address address = new Address();
  address.setStreet("Street Name");
  address.setCity("City Name");
  address.setState("State Name");
  address.setZipCode("Zip-Code Value");

  customer.setCustomerAddress(address);

  // SessionFactory gives us a factory of sessions
  // Usually SessionFactory is been configured by the 
  // configuration file named as hibernate.cfg.xml
  // buildSessionFactory() builds the sessionFactory for us
  SessionFactory sessionFactory = new Configuration().
    configure().buildSessionFactory();

  // Session is created by calling openSession()
  // method on SessionFactory object
  Session session = sessionFactory.openSession();
  session.beginTransaction();

  // Our Transaction Code goes here 
  // i.e save, load , merge and remove
  // Lets save our Customer object created
  // above using sessions save method.
  session.save(customer);

  // Committing the transaction in order to save. 
  session.getTransaction().commit();
  // Closing the session
  session.close();
 }
}



Output of the program : 





















 




Video tutorial to demonstrate how to implement Component Mapping by @Embedded annotation in Hibernate using JPA.








Video tutorial to demonstrate how to create Composite Primary Keys by @Embeddable annotation in Hibernate using JPA.










How to retrieve an object from database by primary key using Hibernate Framework ?.

Program to demonstrate how to retrieve an object from database by primary key using Hibernate Framework.

A simple POJO class (model) Customer.java, whose object we want to store and than retrieve back using primary key from database using Hibernate.

package com.hubberspot.hibernate.examples;

import javax.persistence.Entity;
import javax.persistence.Id;

// @Entity to tell Hibernate that we need this Model
// class to get store in database as a table by name
// Customer
@Entity 
public class Customer {

 // @Id to tell Hibernate that we need this Model
 // class having customerId as a Primary Key in the
 // table Customer created by @Entity
 @Id
 private int customerId;
 private String customerName;

 public int getUserId() {
  return customerId;
 }
 public void setUserId(int userId) {
  this.customerId = userId;
 }

 public String getUserName() {
  return customerName;
 }
 public void setUserName(String userName) {
  this.customerName = userName;
 }
}




Hibernate Configuration XML file


<?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/customerdb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">root</property>

 <!-- SQL dialect -->
 <property name="dialect">
  org.hibernate.dialect.MySQL5Dialect
 </property>

 <!-- Drop and re-create the database schema on startup  -->
 <property name="hbm2ddl.auto">create</property>

 <!-- Mapping class entry into configuration xml for annotated classes -->
 <mapping class="com.hubberspot.hibernate.examples.Customer" />

  </session-factory>
</hibernate-configuration>


A simple test class to save and than retrieve an object from database using the primary key.

package com.hubberspot.hibernate.examples;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateTest {
 public static void main(String[] args) {

  // Lets create a Customer Object 
  Customer customer = new Customer();

  customer.setUserId(1);
  customer.setUserName("Jonty");  

  // SessionFactory gives us a factory of sessions
  // Usually SessionFactory is been configured by the 
  // configuration file named as hibernate.cfg.xml
  // buildSessionFactory() builds the sessionFactory for us
  SessionFactory sessionFactory = new Configuration().
    configure().buildSessionFactory();

  // Session is created by calling openSession()
  // method on SessionFactory object
  Session session = sessionFactory.openSession();
  session.beginTransaction();

  // Our Transaction Code goes here 
  // i.e save, load , merge and remove
  // Lets save our Customer object created
  // above using sessions save method.
  session.save(customer);

  // Committing the transaction in order to save. 
  session.getTransaction().commit();
  // Closing the session
  session.close();

  // Pointing the customer to null in order to  
  // demonstrate how to fetch / retrieve the object 
  customer = null;

  // again opening a session from SessionFactory
  session = sessionFactory.openSession();
  session.beginTransaction();

  // We use get method of the session for retrieving
  // the object from the database if we know the primary key
  // for which we want to retrieve. 
  // The get method takes in two arguments one is class object
  // for which we want to fetch record and second is the 
  // primary key.
  customer = (Customer) session.get(Customer.class, 1);
  
  // finally printing the retrieved customer name based on the 
  // primary key passed
  System.out.println("Customer Name retrived is : " + customer.getUserName());
 }
}



Output of the program : 


 

How to save an Object in database using Hibernate Framework through Annotations ?.

Program to demonstrate how to save an Object in database using Hibernate Framework through Annotations.

A simple POJO class (model) Customer.java, whose object we want to store in database using Hibernate.

package com.hubberspot.hibernate.examples;

import javax.persistence.Entity;
import javax.persistence.Id;

// @Entity to tell Hibernate that we need this Model
// class to get store in database as a table by name
// Customer
@Entity 
public class Customer {

 // @Id to tell Hibernate that we need this Model
 // class having customerId as a Primary Key in the
 // table Customer created by @Entity
 @Id
 private int customerId;
 private String customerName;

 public int getUserId() {
  return customerId;
 }
 public void setUserId(int userId) {
  this.customerId = userId;
 }

 public String getUserName() {
  return customerName;
 }
 public void setUserName(String userName) {
  this.customerName = userName;
 }
}




Hibernate Configuration XML file


<?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/customerdb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">root</property>

 <!-- SQL dialect -->
 <property name="dialect">
  org.hibernate.dialect.MySQL5Dialect
 </property>

 <!-- Drop and re-create the database schema on startup  -->
 <property name="hbm2ddl.auto">create</property>

 <!-- Mapping class entry into configuration xml for annotated classes -->
 <mapping class="com.hubberspot.hibernate.examples.Customer" />

  </session-factory>
</hibernate-configuration>

A simple test class to run and save object into database.

package com.hubberspot.hibernate.examples;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateTest {
 public static void main(String[] args) {

  // Lets create a Customer Object 
  Customer customer = new Customer();

  customer.setUserId(1);
  customer.setUserName("Jonty");  

  // SessionFactory gives us a factory of sessions
  // Usually SessionFactory is been configured by the 
  // configuration file named as hibernate.cfg.xml
  // buildSessionFactory() builds the sessionFactory for us
  SessionFactory sessionFactory = new Configuration().
    configure().buildSessionFactory();

  // Session is created by calling openSession()
  // method on SessionFactory object
  Session session = sessionFactory.openSession();
  session.beginTransaction();

  // Our Transaction Code goes here 
  // i.e save, load , merge and remove
  // Lets save our Customer object created
  // above using sessions save method.
  session.save(customer);

  session.getTransaction().commit();
  session.close();

 }
}




Output of the program :




How to create Hibernate's SessionFactory and Session Using Hibernate's Configuration file ?.

Program to demonstrate how to create Hibernate's SessionFactory and Session Using Hibernate's Configuration file in Java

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateTest {

   public static void main(String[] args) {
  
        // SessionFactory gives us a factory of sessions
    // Usually SessionFactory is been configured by the 
 // configuration file named as hibernate.cfg.xml
 // buildSessionFactory() builds the sessionFactory for us
 SessionFactory sessionFactory = new Configuration().
   configure().buildSessionFactory();
  
 // Session is created by calling openSession()
 // method on SessionFactory object
 Session session = sessionFactory.openSession();
 session.beginTransaction();

 // Our Transaction Code goes here 
 // i.e save, load , merge and remove
  
 session.getTransaction().commit();
 session.close();

   }
}




Hibernate Configuration file as : "hibernate.cfg.xml"



How to develop your first Hibernate Application : Step by Step

A simple post providing step by step development of your first Hibernate Application in Java

1. Create a new Database Schema and Table in MySQL -

Since I am demonstrating this application on MySQL database server, please ensure you have MySQL database installed on your machine. At the time of installation please set username and password and remember it. Now after installation login to MySQL database using username and password from : Start -> Programs -> MySQL -> MySQL server 5.1 -> MySQL Command Line Client .

a. Create the database named customerdb


Create database customerdb;

b. Switch to the database

use customerdb;

c. Create table named customer

CREATE TABLE customer (     
customerId INT PRIMARY KEY AUTO_INCREMENT,
customerName VARCHAR(50),
customerEmail VARCHAR(60),
customerPhone INT(15));





















2. Create a new Java Project in Eclipse -
After creating database and table let's move on to create a new Java project in Eclipse. In order to create a new Java project in Eclipse select File -> New -> Java Project to create a new Java project

A window appears as : 'Create a Java Project'. Enter Project name and click finish.


3. Add JDBC Driver and Hibernate specific libraries -
a. Add the Hibernate specific jars to it. It can be downloaded from link : http://sourceforge.net/projects/hibernate/files/hibernate4/
b. Add driver jar for specific database say am using MySql database here so I am adding the jar by name as : 'mysql-connector-java-5.1.20-bin.jar'



4. Create a JavaBean (POJO) Class -

In the project created on step 2, in the src folder create a new package say 'com.hubberspot.hibernate'. Add a new Java class and name it as Customer.java. The code is given below :



package com.hubberspot.hibernate;


public class Customer {

 private Integer customerId;
 private String customerName;
 private String customerEmail;
 private String customerPhone;

 public Customer() {

 }


 public Integer getCustomerId() {
  return customerId;
 }


 public void setCustomerId(Integer customerId) {
  this.customerId = customerId;
 }


 public String getCustomerName() {
  return customerName;
 }


 public void setCustomerName(String customerName) {
  this.customerName = customerName;
 }


 public String getCustomerEmail() {
  return customerEmail;
 }


 public void setCustomerEmail(String customerEmail) {
  this.customerEmail = customerEmail;
 }


 public String getCustomerPhone() {
  return customerPhone;
 }


 public void setCustomerPhone(String customerPhone) {
  this.customerPhone = customerPhone;
 }



}




5. Create Hibernate Configuration File -

Hibernate uses a configuration file by default name as 'hibernate.cfg.xml'. It uses this file to make database connections and necessary resource mapping file entries. It also acts and helps Hibernate as a metadata for creating a fully fledged database environment.
It is been placed in the src folder of our Java project. The Hibernate Configuration file with name 'hibernate.cfg.xml'is given below :

<?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/customerdb</property>
  <property name="connection.username">root</property>
  <property name="connection.password">root</property>

  <!-- SQL dialect -->
  <property name="dialect">
   org.hibernate.dialect.MySQL5Dialect
  </property>

  <mapping resource="Customer.hbm.xml" />

 </session-factory>
</hibernate-configuration>



It requires following properties for effective integration of Hibernate with our application -

a. connection.driver_class : It is the JDBC Connection class for the database you are intent to use.
b. connection.url : It is the JDBC URL to the database you are intent to use in your application.
c. connection.username : Username to the database which will help us to connect.
d. connection.password : Password to the database which will help us to connect.
e. dialect : Dialect property is a special property and a mandatory one. Hibernate communicates with the underlying database using dialect class specified in the property. It acts as a metadata of database for Hibernate stating few information about database as whether it allows identity column , altering relational tables , indexes and constraints etc ...
f. mapping resource : This property helps Hibernate about the Entities used in the application and it has name of hbm xml file which tells Hibernate that this entity has a separate xml, which will have information that helps Hibernate to map object state to relational tables.



6. Create Hibernate Mapping File -
Hibernate Mapping files are the configuration files to Hibernate which helps it to map objects to relational database. It helps Hibernate to persist objects to database. This file generally follows a naming convension having the name of table in database + .hbm.xml . In our case it is Customer.hbm.xml . It is been placed in the src folder of our Java project.


<?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>
 <class name="com.hubberspot.hibernate.Customer" table="customer"
  catalog="customerdb">
  <id name="customerId" type="java.lang.Integer">
   <column name="customerId"></column>
   <generator class="identity"></generator>
  </id>

  <property name="customerName" type="java.lang.String">
   <column name="customerName" length="50"></column>
  </property>

  <property name="customerEmail" type="java.lang.String">
   <column name="customerEmail" length="60"></column>
  </property>

  <property name="customerPhone" type="java.lang.Long">
   <column name="customerPhone" length="15"></column>
  </property>

 </class>
</hibernate-mapping>



7. Create a HibernateTest.java class to run the application -

package com.hubberspot.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateTest {
 public static void main(String[] args) {

  // SessionFactory gives us a factory of sessions
  // Usually SessionFactory is been configured by the 
  // configuration file named as hibernate.cfg.xml
  // buildSessionFactory() builds the sessionFactory for us
  SessionFactory sessionFactory = new Configuration().
    configure().buildSessionFactory();

  // Session is created by calling openSession()
  // method on SessionFactory object
  Session session = sessionFactory.openSession();
  // Creating a transaction from session
  Transaction tx = session.beginTransaction();

  // Creating a Customer object 
  Customer customer = new Customer();
  // setting customer name , email and phone
  customer.setCustomerName("hubberspot");
  customer.setCustomerEmail("jonty@hubberspot.com");
  customer.setCustomerPhone(89289867L);
  // Saving the Customer into the database 
  session.save(customer);
  // Commiting the transaction
  session.getTransaction().commit();
  // closing the session
  session.close();

 }
}




Table data in the database -


 
© 2021 Learn Java by Examples Template by Hubberspot