MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create Database Table using Hibernate

This article is going to describe how to create a database table from database using hibernate.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Introduction

A hibernate is an object relational mapping (ORM) tool, that is used to manipulate database tables as class and their object. We are using hibernate 3.6 version to create a database table.

Common Hibernate Terms:

A Hibernate is an object relational tool for database used in java to provide the accessibility of database contents using objects.

hibernate.cfg : This is a hibernate configuration file, where database connection settings and all the required settings are listed to communicate with the database. This is a xml file that configures setting in xml tag format as listed below:

Listing 1: hibernate.cfg

<?xml version='1.0' encoding='utf-8'?> : This is the first tag of hibernate.cfg file that describe the xml version and encoding format for the xml file.
<!DOCTYPE hibernate-configuration
        "-//Hibernate/Hibernate Configuration DTD 3.1"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.1.dtd">

This tag is the xml document type tag, which provides the required information about the document or hibernate configuration xml file.

<hibernate-configuration> : This is next and parent tag for the hibernate configuration. It is the base tag, containg all the hibernate configuration setting in its sub tags.

<session-factory> : This is sub tag of <hibernate-configuration> that hold all the required properties to communicate with the database, like database connection setting url, usernate, password and etc.

<property name = “---“>---</property> : This is the sub tag of <session-factory>, which describe all the required properties in order to communicate with the database like connection properties for database. All the required properties are listed below:

Database Connection Properties:

Driver Class Property :

This property defines the database connection string, which is database specific.

<property name="connection.driverclass">org.mm.mysql.Driver</property>

Connection Url Property :

This property defines the database connection url.

        <property name="connection.url">jdbc:mysql://localhost:3306/AJO_DB</property>

Database Username Property :

This property defines the database user name.

     <property name="connection_userid">root</property>

Database Password Property :

This property defines the database password.

<property name="connection_pwd">root</property>

JDBC Connection Pool Property :

This property defines the used pool size for the hibernate

<property name="connection_poolsize">1</property>

SQL Dialect Property :

This property informs the hibernate about the used database so that hibernate could database specific queries automatically.

<property name="dialect">org.hibernate.dialect.MySQL</property>

Second Level Cache Property :

This property tells the hibernate, whether there is a cache provider or not.

   <property name="cache.providerclass">org.hibernate.NoCacheProvider</property>

Show Sql Proper :

This property informs the hibernate to print all the executing queries on to the console.

 <property name="cache.providerclass">org.hibernate.NoCacheProvider</property>

hbm2ddl.auto property :

This property tell the hibernate to create or update database schema, while executing.

       <property name="cache.providerclass">org.hibernate.NoCacheProvider</property>

Mapping Tag :

This tag inform the hibernate, which class is to be treated as database or entity class.

   <mapping class="com.ajo.common.db_TestTable"/>

Listing 2: Database Connection Properties

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-config PUBLIC
        "-//Hibernate/Hibernate Config DTD 3.1//EN"
        "http://www.hibernate.org/dtd/hibernate-config-3.1.dtd">

<hibernate-config>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.mm.mysql.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/AJO_DB</property>
        <property name="connection_userid">root</property>
        <property name="connection_pwd">root</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection_pool_size">true</property>

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">1</property>

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

        <!-- Names the annotated entity class -->
        <mapping class="com.ajo.common_dto.TestTable"/>

    </session-factory>

</hibernate-configuration>

In the mapping tag of the hibernate.cfg file, TestTable was defined in the class attribute that represent a pojo class class, being referred to the database table.

The TestTale.Java File : This file defines a pojo class that is bean class having setter and getter methods for defines class variables. The class name is being referred to the database table sometimes and class variable name can be referred to the database attribute names respectively.

But these names can be altered as user defined using annotations and their properties.

To define a class as database table name, @Entity annotation has to write before the class declaration that tell the hibernate to use this class database entity class.

@Entity
class TestTable;

This annotation was defined in the class name javax.persistance.Entity class.

import javax.persistence.Entity;

To define a primary key in the hibernate, annotation name @Id need to place before the class variable declaration.

@Id
int id;

This annotation was defined in the class name javax.persistance.Id;

import javax.persistence.Id;

To modify the database table name not same as the class name, name attribute of the @Entity annotation is used as follows:

@Entity (name = “Database_Table_Name”)

To modify the attribute name of table not same as the class variable names, use annotation @Column with attribute name as follows:

@Column (name = “Attribute_name”)

This annotation is defined in the javax.persistance.Column

import javax.persistence.Column;

We can also place the @Id and @Column annotation before the getter methods instead of class variable declaration.

@Id
public int getId(){
return id;
}

Listing 3: TestTale.Java File

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

@Entity (name = “Test_Table”)
public class TestTable {
	
private int id;

private String firstName,lastName;
@Id
public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
@Column (name = “FName”)
public String getFirstName() {
	return firstName;
}
public void set.FirstName(String firstName) {
	this.firstName = firstName;
}
@Column (name = “LName”)
public String getLastName() {
	return lastName;
}
public void set.LastName(String lastName) {
	this.lastName = lastName;
}
}

To add data in to the database, it is necessary to go with the listed steps:

Add a configuration file with the class:

Configuration cfg = new Configuration();
	cfg.configure("hibernate.cfg.xml");

Create a session factory object that should be created for once for an application.

SessionFactory factory = cfg.buildSessionFactory();

Create a session object from session factory object, this is request specific.

Session session = factory.openSession();

Create a transaction object from session session_beginTransaction()

Transaction t = session.begin_Transaction();

Create a pojo class object and assign data using setter methods.

TestTable e1 = new TestTable ();
	e1.setId(115);
	e1.setFirstName("sonoo");
	e1.setLastName("jaiswal");

Now call persist method of session class to save data object into the database

session.persist(e1);

Now Commit the database entry using commit() method of transaction class

t.commit();

Listing 4: AddToDB.java class

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

public class AddToDB {	
	int i = 0;	
public static void main(String[] args) {	
	new StoreData().i = 5;	
	//creating configuration object
	Configuration cfg=new Configuration();
	cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file	
	//creating seession factory object
	SessionFactory factory=cfg.buildSessionFactory();	
	//creating session object
	Session session=factory.openSession();	
	//creating transaction object
	Transaction t=session.beginTransaction();
	TestTable e1=new TestTable ();
	e1.setId(115);
	e1.setFirstName("sonoo");
	e1.setLastName("jaiswal");
	session.persist(e1);//persisting the object
	t.commit();//transaction is commited
	session.close();
	System.out.println("successfully saved");
	}
}


Output:

Add two library into your project as Hibernate3 and MySql Connector

Figure 1: Add two library into your project as Hibernate3 and MySql Connector

User Library jar files for Hibernate 3.6 and MySql Connector

Figure 2: User Library jar files for Hibernate 3.6 and MySql Connector

To run AddToDb Class from eclipse

Figure 3: To run AddToDb Class from eclipse

Result of hibernate running queries showing in the console, inserting a record in the database table

Figure 4: Result of hibernate running queries showing in the console, inserting a record in the database table

Conclusion:

In this article, we learned about:

  • Creating hibernate configuration file
  • Create POJO class for hibernate database table
  • Create Hibernate connection class to communicate with database.


Working in Software Development domain from 7 years now and is well equipped with programming languages like HTML, CSS, Java, PHP, .NET etc.

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login