Pin It

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), 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
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
 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"

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

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

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


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();


  // 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().

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

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



Output of the program :

Please Give Us Your 1 Minute In Sharing This Post!
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
© 2012 Learn Java by Examples Template by Hubber Spot