SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Hibernate
http://www.java2all.com
Java Hibernate
introduction
http://www.java2all.com
Hibernate is an open source object relational mapping tool used
in Java programming.
Hibernate allows data to be inserted, removed or changed in a
database without paying a lot of attention to how it gets there.
Hibernate was founded by Mr. Gavin King, an Australian
developer who needed to solve a problem and ended up creating
Hibernate, an open source tool that is amazingly useful with JAVA.
The central idea of Hibernate is this: “JAVA programmers are
used to creating POJOs [Plain Old Java Objects] in Java.
http://www.java2all.com
http://www.java2all.com
So why do they need a second language like SQL, to put or apply
(persist) those POJOs into the database? ”
Hibernate does object-relational persistence and querying.
That means Hibernate puts whole objects into a relational
database and pulls whole objects out of a relational database.
When Can I Use Hibernate?
Hibernate can be used in any Java program that needs to access a
relational database. Hibernate does not need an application server to run.
http://www.java2all.com
When Should I Use Hibernate?
There are main three points at where Hibernate is use if :
(1)There is a non-trivial application
(2) There are more than 10 tables in the relational DB.
(3) The application uses an object-oriented Domain Model.
If the application does a lot of business logic—and does much
more than just display tables of data on a webpage—then it is a good
candidate for Hibernate.
http://www.java2all.com
Hibernate is best in applications with complex data models, with
hundreds of tables and complex inter-relationships.
So Hibernate maps the java classes to the database tables. It also
provides the data query and retrieval facilities that reduce the
development time.
Note:
Domain Model means an object model of the domain that
incorporates both behavior and data
Note:
Hibernate is most useful with object-oriented domain modes and
business logic in the Java based middle-tier.
It is not the best solutions for data centric application that only
uses the stored-procedures to implement the business logic in database.
Java Hibernate
Architecture
http://www.java2all.com
To use Hibernate, it is required to create Java classes that
represents a table in the database and then map the instance variable in
the class with the columns in the database.
Then Hibernate can be used to perform operations on the
database like select, insert, update and delete the records in the table.
Hibernate automatically creates the query to perform these
operations.
For that Hibernate architecture has three main components:
(1) Connection Management
(2) Transaction management
(3) Object relational mapping
The following diagram describes the high level architecture of hibernate:
http://www.java2all.com
http://www.java2all.com
The above diagram shows that Hibernate is using the
database and configuration Data(Hibernate.prpperties and XML
Mappping) to provide persistence services (and persistent
objects) to the application.
(1) Connection Management:
Hibernate Connection management service provide efficient
management of the database connections. Database connection is
the most expensive part of interacting with the database as it
requires a lot of resources of open and close the database
connection.
http://www.java2all.com
(2) Transaction management:
Transaction management service provides the ability to the user
to execute more than one database statements at a time.
(3) Object relational mapping:
Object relational mapping is technique of mapping the data
representation from an object model to a relational data model.
This part of hibernate is used to select, insert, update and delete
the records form the underlying table.
http://www.java2all.com
When we pass an object to a Session.save() method, Hibernate
reads the state of the variables of that object and executes the necessary
query.
Hibernate provides a lot of flexibility in use. It is called "Lite"
architecture when we only use the object relational mapping component.
While in "Full Cream" architecture all the three components
object Relational mapping, Connection Management and transaction
Management) are used.
http://www.java2all.com
http://www.java2all.com
NOTE:
Hibernate is very good tool as far as object relational mapping is
concern, but in terms of connection management and transaction
management, it is lacking in performance and capabilities.
So usually hibernate is being used with other connection management
and transaction management tools.
For example apache DBCP is used for connection pooling with
the Hibernate.
Java Hibernate Example
http://www.java2all.com
Write a java hibernate example or program to insert a record in
database.
NOTE:
The all theoretical steps, source code and program to insert a
record in database is described below and the steps you should perform
in MyEclipse to do java hibernate example is available in above video.
Step 1: Right Click on project and select My Eclipse and then select the
Add Hibernate Capabilities.
Step 2: Now Click on Next Button.
Step 3: Again Click on Next Button.
Step 4: Select the appropriate database at DB Driver combo box and
then click on Next button.
http://www.java2all.com
Step 5: Select the appropriate Java package by click on Browse button.
Step 6: Then click on OK button.
From here now the programming files will be generated and still
total 8 steps are remaining that is mentioned below this tutorial is
especially created for beginners to do java hibernate example.
Step 7: Then click on Finish button So it will automatically create two
files:
1. This is an xml file(hibernate configuration) which is available
in the src like hibernate.cfg.xml which contains the properties of
connection with database for session-factory like username, url, dialect,
profile, password, driver_class.
http://www.java2all.com
http://www.java2all.com
2. Second is a HibernateSessionFactory.java file which is available at the
com package for handling the session and its properties.
Hibernate uses the hibernate.cfg.xml to create the connection
pool and setup required environment.
http://www.java2all.com
1. hibernate.cfg.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">
<!-- Generated by MyEclipse Hibernate Tools.-->
<hibernate-configuration>
<session-factory>
<property name="connection.username">classiccars</property>
<property name="connection.url">jdbc:derby://localhost:1527/myeclipse</property>
<property name="dialect">org.hibernate.dialect.DerbyDialect</property>
<property name="myeclipse.connection.profile">MyEclipse Derby</property>
<property name="connection.password">myeclipse</property>
<propertyname="connection.driver_class">
org.apache.derby.jdbc.ClientDriver</property>
</session-factory>
</hibernate-configuration>
1. hibernate.cfg.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">
<!-- Generated by MyEclipse Hibernate Tools.-->
<hibernate-configuration>
<session-factory>
<property name="connection.username">classiccars</property>
<property name="connection.url">jdbc:derby://localhost:1527/myeclipse</property>
<property name="dialect">org.hibernate.dialect.DerbyDialect</property>
<property name="myeclipse.connection.profile">MyEclipse Derby</property>
<property name="connection.password">myeclipse</property>
<propertyname="connection.driver_class">
org.apache.derby.jdbc.ClientDriver</property>
</session-factory>
</hibernate-configuration>
http://www.java2all.com
Hibernate supports many database.
With the use of the Hibernate (Object/Relational Mapping and
Transparent Object Persistence for Java and SQL Databases), we can use
the following databases dialect type property:
http://www.java2all.com
DB2 - org.hibernate.dialect.DB2 Dialect
Oracle (any version) - org.hibernate.dialect.OracleDialect
Oracle 9 - org.hibernate.dialect.Oracle9Dialect
MySQL - org.hibernate.dialect.MySQLDialect
PostgreSQL - org.hibernate.dialect.PostgreSQLDialect
Sybase - org.hibernate.dialect.SybaseDialect
Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect
Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect
HypersonicSQL - org.hibernate.dialect.HSQ LDialect
Informix - org.hibernate.dialect.InformixDialect
Ingres - org.hibernate.dialect.IngresDialect
Interbase - org.hibernate.dialect.InterbaseDialect
Pointbase - org.hibernate.dialect.PointbaseDialect
Mckoi SQL - org.hibernate.dialect.MckoiDialect
Progress - org.hibernate.dialect.ProgressDialect
FrontBase - org.hibernate.dialect.FrontbaseDialect
SAP DB - org.hibernate.dialect.SAPDBDialect
http://www.java2all.com
2. HibernateSessionFactory.java:
package com;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory
{
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static
{
try
{
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
}
catch(Exception e)
{
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
2. HibernateSessionFactory.java:
package com;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory
{
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static
{
try
{
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
}
catch(Exception e)
{
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
http://www.java2all.com
private HibernateSessionFactory()
{
}
public static Session getSession() throws HibernateException
{
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen())
{
if (sessionFactory == null)
{
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession(): null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory()
{
try
{
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
}
catch (Exception e)
{
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory()
{
}
public static Session getSession() throws HibernateException
{
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen())
{
if (sessionFactory == null)
{
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession(): null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory()
{
try
{
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
}
catch (Exception e)
{
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
http://www.java2all.com
public static void closeSession() throws HibernateException
{
Session session = (Session) threadLocal.get();
threadLocal.set(null); if (session != null)
{
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void setConfigFile(String configFile)
{
HibernateSessionFactory.configFile = configFile; sessionFactory = null;
}
public static Configuration getConfiguration()
{
return configuration;
}
}
public static void closeSession() throws HibernateException
{
Session session = (Session) threadLocal.get();
threadLocal.set(null); if (session != null)
{
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void setConfigFile(String configFile)
{
HibernateSessionFactory.configFile = configFile; sessionFactory = null;
}
public static Configuration getConfiguration()
{
return configuration;
}
}
http://www.java2all.com
Step 8: Now add resource in mapping tag for the mapping with an appropriate table in
hibernate.cfg.xml file.
<mapping resource=" contact.hbm.xml "/>
It is for mapping for our contact table.
hibernate.cfg.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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">classiccars</property>
<property ame="connection.url">jdbc:derby://localhost:1527/myeclipse</property>
<property name="dialect">org.hibernate.dialect.DerbyDialect</property>
<property name="myeclipse.connection.profile">MyEclipse Derby</property>
<property name="connection.password">myeclipse</property>
<property name="connection.driver_class"> org.apache.derby.jdbc.ClientDriver</property>
<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernate.cfg.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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">classiccars</property>
<property ame="connection.url">jdbc:derby://localhost:1527/myeclipse</property>
<property name="dialect">org.hibernate.dialect.DerbyDialect</property>
<property name="myeclipse.connection.profile">MyEclipse Derby</property>
<property name="connection.password">myeclipse</property>
<property name="connection.driver_class"> org.apache.derby.jdbc.ClientDriver</property>
<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
http://www.java2all.com
Step 9: -Now Create the First Persistence Class(java file).
Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database 
table so We can configure the variables to map to the database column.
package com;
public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;
public String getEmail() {
return email;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setEmail(String string) {
email = string;
}
public void setFirstName(String string) {
firstName = string;
}
public void setLastName(String string) {
lastName = string;
}
package com;
public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;
public String getEmail() {
return email;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setEmail(String string) {
email = string;
}
public void setFirstName(String string) {
firstName = string;
}
public void setLastName(String string) {
lastName = string;
}
http://www.java2all.com
public long getId() {
return id;
}
public void setId( long l) {
id = l;
} }
Step 10: Create the contact.hbm.xml file in a default package.
http://www.java2all.com
contact.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="com.Contact" table="APP.CONTACT">
<id name="id" type="long" column="ID" >
<generator class="assigned"/> </id>
<property name="firstName">
<column name="FIRSTNAME" /> </property>
<property name="lastName">
<column name="LASTNAME"/> </property>
<property name="email">
<column name="EMAIL"/> </property> </class>
</hibernate-mapping>
contact.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="com.Contact" table="APP.CONTACT">
<id name="id" type="long" column="ID" >
<generator class="assigned"/> </id>
<property name="firstName">
<column name="FIRSTNAME" /> </property>
<property name="lastName">
<column name="LASTNAME"/> </property>
<property name="email">
<column name="EMAIL"/> </property> </class>
</hibernate-mapping>
http://www.java2all.com
package hibernate_demo;
import java.util.Scanner;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.Contact;
public class FirstExample {
public static void main(String [] args)
{
Session session = null;
try {
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
System.out.println( "Inserting Record…………");
Contact contact = new Contact();
Scanner s = new Scanner(System.in);
System.out.println("Enter Id : ");
int id = s.nextInt(); contact.setId(id);
package hibernate_demo;
import java.util.Scanner;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.Contact;
public class FirstExample {
public static void main(String [] args)
{
Session session = null;
try {
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
System.out.println( "Inserting Record…………");
Contact contact = new Contact();
Scanner s = new Scanner(System.in);
System.out.println("Enter Id : ");
int id = s.nextInt(); contact.setId(id);
Step 11: Now create the java file by which the data is inserting in 
the table (CONTACT) at database.
http://www.java2all.com
System.out.println("Enter First name : ");
String firstname = s.next();
contact.setFirstName(firstname);
System.out.println("Enter Last name : ");
String lastname = s.next();
contact.setLastName(lastname);
System.out.println("Enter Email id : ");
String email = s.next();
contact.setEmail(email);
session.save(contact);
System.out.println("Data inserted successfully………");
} catch(Exception e){
System.out.println(e.getMessage());
}
finally {
session.flush(); session.close();
}
} } 
System.out.println("Enter First name : ");
String firstname = s.next();
contact.setFirstName(firstname);
System.out.println("Enter Last name : ");
String lastname = s.next();
contact.setLastName(lastname);
System.out.println("Enter Email id : ");
String email = s.next();
contact.setEmail(email);
session.save(contact);
System.out.println("Data inserted successfully………");
} catch(Exception e){
System.out.println(e.getMessage());
}
finally {
session.flush(); session.close();
}
} } 
http://www.java2all.com
Hibernate Session is the main runtime interface between a Java 
application and Hibernate. First we are required to get the Hibernate 
Session.SessionFactory allows application to create the Hibernate 
Sesssion by reading the configuration from hibernate.cfg.xml file.
 
Then the save method on session object is used to save the 
contact information to the database:
session.save(contact)
 
Step 12: Select a MyEclipse Hibernet view and creating a table 
(CONTACT) in APP at MyEclipse Derby.
 
Step 13: Now Start the Database, Then check the message in Console.
http://www.java2all.com
Console:
 
Apache Derby Network Server - 10.2.2.0 - (485682) started and ready to 
accept connections on port 1527 at 2012-12-29 09:34:17.187 GMT
 
Step 14: After getting such message in Console, Run the 
FirstExample.java file as a java application and following output will 
display in the Console.
http://www.java2all.com
Console:
log4j:WARN No appenders could be found for logger 
(org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record…………
Enter Id : 
1
Enter First name : 
java2all
Enter Last name : 
Learn Java Online
Enter Email id : 
contact@java2all.com
Data inserted successfully………
This is a simple java hibernate example to insert a record in database.

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Enterprise java unit-1_chapter-1
Enterprise java unit-1_chapter-1Enterprise java unit-1_chapter-1
Enterprise java unit-1_chapter-1
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Enterprise java unit-2_chapter-1
Enterprise  java unit-2_chapter-1Enterprise  java unit-2_chapter-1
Enterprise java unit-2_chapter-1
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 

Andere mochten auch

Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernatehr1383
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To HibernateAmit Himani
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesBrett Meyer
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with codekamal kotecha
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Document retrieval using clustering
Document retrieval using clusteringDocument retrieval using clustering
Document retrieval using clusteringeSAT Journals
 
High dimesional data (FAST clustering ALG) PPT
High dimesional data (FAST clustering ALG) PPTHigh dimesional data (FAST clustering ALG) PPT
High dimesional data (FAST clustering ALG) PPTdeepan v
 
Cluster Evaluation in Catalonia
Cluster Evaluation in Catalonia Cluster Evaluation in Catalonia
Cluster Evaluation in Catalonia TCI Network
 
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf Conference
 
Профессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseПрофессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseAlexander Granin
 
Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникOrm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникAlina Dolgikh
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionEr. Gaurav Kumar
 
Hibernate an introduction
Hibernate   an introductionHibernate   an introduction
Hibernate an introductionjoseluismms
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate IntroductionRanjan Kumar
 

Andere mochten auch (20)

Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Document retrieval using clustering
Document retrieval using clusteringDocument retrieval using clustering
Document retrieval using clustering
 
High dimesional data (FAST clustering ALG) PPT
High dimesional data (FAST clustering ALG) PPTHigh dimesional data (FAST clustering ALG) PPT
High dimesional data (FAST clustering ALG) PPT
 
JAX-WS Basics
JAX-WS BasicsJAX-WS Basics
JAX-WS Basics
 
Cluster Evaluation in Catalonia
Cluster Evaluation in Catalonia Cluster Evaluation in Catalonia
Cluster Evaluation in Catalonia
 
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Профессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseПрофессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом Enterprise
 
Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникOrm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел Вейник
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic Introduction
 
Hibernate an introduction
Hibernate   an introductionHibernate   an introduction
Hibernate an introduction
 
Hibernate
HibernateHibernate
Hibernate
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
 

Ähnlich wie Java Hibernate Programming with Architecture Diagram and Example

Ähnlich wie Java Hibernate Programming with Architecture Diagram and Example (20)

Hibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaHibernate Interview Questions | Edureka
Hibernate Interview Questions | Edureka
 
Hibernate.pdf
Hibernate.pdfHibernate.pdf
Hibernate.pdf
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jj
 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tool
 
Introduction to Hibernate
Introduction to HibernateIntroduction to Hibernate
Introduction to Hibernate
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Hibernate
HibernateHibernate
Hibernate
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate Interview Questions and Answers
Hibernate Interview Questions and AnswersHibernate Interview Questions and Answers
Hibernate Interview Questions and Answers
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Learn HIBERNATE at ASIT
Learn HIBERNATE at ASITLearn HIBERNATE at ASIT
Learn HIBERNATE at ASIT
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate Notes
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 

Mehr von kamal kotecha

Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of javakamal kotecha
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7kamal kotecha
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operatorkamal kotecha
 

Mehr von kamal kotecha (17)

Java rmi
Java rmiJava rmi
Java rmi
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
Jsp element
Jsp elementJsp element
Jsp element
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Interface
InterfaceInterface
Interface
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
Class method
Class methodClass method
Class method
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Control statements
Control statementsControl statements
Control statements
 
Jsp myeclipse
Jsp myeclipseJsp myeclipse
Jsp myeclipse
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 

Kürzlich hochgeladen

Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdfSuman Jyoti
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfrs7054576148
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 

Kürzlich hochgeladen (20)

Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdf
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 

Java Hibernate Programming with Architecture Diagram and Example

  • 3. Hibernate is an open source object relational mapping tool used in Java programming. Hibernate allows data to be inserted, removed or changed in a database without paying a lot of attention to how it gets there. Hibernate was founded by Mr. Gavin King, an Australian developer who needed to solve a problem and ended up creating Hibernate, an open source tool that is amazingly useful with JAVA. The central idea of Hibernate is this: “JAVA programmers are used to creating POJOs [Plain Old Java Objects] in Java. http://www.java2all.com
  • 4. http://www.java2all.com So why do they need a second language like SQL, to put or apply (persist) those POJOs into the database? ” Hibernate does object-relational persistence and querying. That means Hibernate puts whole objects into a relational database and pulls whole objects out of a relational database. When Can I Use Hibernate? Hibernate can be used in any Java program that needs to access a relational database. Hibernate does not need an application server to run.
  • 5. http://www.java2all.com When Should I Use Hibernate? There are main three points at where Hibernate is use if : (1)There is a non-trivial application (2) There are more than 10 tables in the relational DB. (3) The application uses an object-oriented Domain Model. If the application does a lot of business logic—and does much more than just display tables of data on a webpage—then it is a good candidate for Hibernate.
  • 6. http://www.java2all.com Hibernate is best in applications with complex data models, with hundreds of tables and complex inter-relationships. So Hibernate maps the java classes to the database tables. It also provides the data query and retrieval facilities that reduce the development time. Note: Domain Model means an object model of the domain that incorporates both behavior and data Note: Hibernate is most useful with object-oriented domain modes and business logic in the Java based middle-tier. It is not the best solutions for data centric application that only uses the stored-procedures to implement the business logic in database.
  • 8. To use Hibernate, it is required to create Java classes that represents a table in the database and then map the instance variable in the class with the columns in the database. Then Hibernate can be used to perform operations on the database like select, insert, update and delete the records in the table. Hibernate automatically creates the query to perform these operations. For that Hibernate architecture has three main components: (1) Connection Management (2) Transaction management (3) Object relational mapping The following diagram describes the high level architecture of hibernate: http://www.java2all.com
  • 10. The above diagram shows that Hibernate is using the database and configuration Data(Hibernate.prpperties and XML Mappping) to provide persistence services (and persistent objects) to the application. (1) Connection Management: Hibernate Connection management service provide efficient management of the database connections. Database connection is the most expensive part of interacting with the database as it requires a lot of resources of open and close the database connection. http://www.java2all.com
  • 11. (2) Transaction management: Transaction management service provides the ability to the user to execute more than one database statements at a time. (3) Object relational mapping: Object relational mapping is technique of mapping the data representation from an object model to a relational data model. This part of hibernate is used to select, insert, update and delete the records form the underlying table. http://www.java2all.com
  • 12. When we pass an object to a Session.save() method, Hibernate reads the state of the variables of that object and executes the necessary query. Hibernate provides a lot of flexibility in use. It is called "Lite" architecture when we only use the object relational mapping component. While in "Full Cream" architecture all the three components object Relational mapping, Connection Management and transaction Management) are used. http://www.java2all.com
  • 13. http://www.java2all.com NOTE: Hibernate is very good tool as far as object relational mapping is concern, but in terms of connection management and transaction management, it is lacking in performance and capabilities. So usually hibernate is being used with other connection management and transaction management tools. For example apache DBCP is used for connection pooling with the Hibernate.
  • 15. Write a java hibernate example or program to insert a record in database. NOTE: The all theoretical steps, source code and program to insert a record in database is described below and the steps you should perform in MyEclipse to do java hibernate example is available in above video. Step 1: Right Click on project and select My Eclipse and then select the Add Hibernate Capabilities. Step 2: Now Click on Next Button. Step 3: Again Click on Next Button. Step 4: Select the appropriate database at DB Driver combo box and then click on Next button. http://www.java2all.com
  • 16. Step 5: Select the appropriate Java package by click on Browse button. Step 6: Then click on OK button. From here now the programming files will be generated and still total 8 steps are remaining that is mentioned below this tutorial is especially created for beginners to do java hibernate example. Step 7: Then click on Finish button So it will automatically create two files: 1. This is an xml file(hibernate configuration) which is available in the src like hibernate.cfg.xml which contains the properties of connection with database for session-factory like username, url, dialect, profile, password, driver_class. http://www.java2all.com
  • 17. http://www.java2all.com 2. Second is a HibernateSessionFactory.java file which is available at the com package for handling the session and its properties. Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment.
  • 18. http://www.java2all.com 1. hibernate.cfg.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"> <!-- Generated by MyEclipse Hibernate Tools.--> <hibernate-configuration> <session-factory> <property name="connection.username">classiccars</property> <property name="connection.url">jdbc:derby://localhost:1527/myeclipse</property> <property name="dialect">org.hibernate.dialect.DerbyDialect</property> <property name="myeclipse.connection.profile">MyEclipse Derby</property> <property name="connection.password">myeclipse</property> <propertyname="connection.driver_class"> org.apache.derby.jdbc.ClientDriver</property> </session-factory> </hibernate-configuration> 1. hibernate.cfg.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"> <!-- Generated by MyEclipse Hibernate Tools.--> <hibernate-configuration> <session-factory> <property name="connection.username">classiccars</property> <property name="connection.url">jdbc:derby://localhost:1527/myeclipse</property> <property name="dialect">org.hibernate.dialect.DerbyDialect</property> <property name="myeclipse.connection.profile">MyEclipse Derby</property> <property name="connection.password">myeclipse</property> <propertyname="connection.driver_class"> org.apache.derby.jdbc.ClientDriver</property> </session-factory> </hibernate-configuration>
  • 19. http://www.java2all.com Hibernate supports many database. With the use of the Hibernate (Object/Relational Mapping and Transparent Object Persistence for Java and SQL Databases), we can use the following databases dialect type property:
  • 20. http://www.java2all.com DB2 - org.hibernate.dialect.DB2 Dialect Oracle (any version) - org.hibernate.dialect.OracleDialect Oracle 9 - org.hibernate.dialect.Oracle9Dialect MySQL - org.hibernate.dialect.MySQLDialect PostgreSQL - org.hibernate.dialect.PostgreSQLDialect Sybase - org.hibernate.dialect.SybaseDialect Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect HypersonicSQL - org.hibernate.dialect.HSQ LDialect Informix - org.hibernate.dialect.InformixDialect Ingres - org.hibernate.dialect.IngresDialect Interbase - org.hibernate.dialect.InterbaseDialect Pointbase - org.hibernate.dialect.PointbaseDialect Mckoi SQL - org.hibernate.dialect.MckoiDialect Progress - org.hibernate.dialect.ProgressDialect FrontBase - org.hibernate.dialect.FrontbaseDialect SAP DB - org.hibernate.dialect.SAPDBDialect
  • 21. http://www.java2all.com 2. HibernateSessionFactory.java: package com; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; public class HibernateSessionFactory { private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch(Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } 2. HibernateSessionFactory.java: package com; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; public class HibernateSessionFactory { private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch(Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } }
  • 22. http://www.java2all.com private HibernateSessionFactory() { } public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession(): null; threadLocal.set(session); } return session; } public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession(): null; threadLocal.set(session); } return session; } public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } }
  • 23. http://www.java2all.com public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } public static Configuration getConfiguration() { return configuration; } } public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } public static Configuration getConfiguration() { return configuration; } }
  • 24. http://www.java2all.com Step 8: Now add resource in mapping tag for the mapping with an appropriate table in hibernate.cfg.xml file. <mapping resource=" contact.hbm.xml "/> It is for mapping for our contact table. hibernate.cfg.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"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="connection.username">classiccars</property> <property ame="connection.url">jdbc:derby://localhost:1527/myeclipse</property> <property name="dialect">org.hibernate.dialect.DerbyDialect</property> <property name="myeclipse.connection.profile">MyEclipse Derby</property> <property name="connection.password">myeclipse</property> <property name="connection.driver_class"> org.apache.derby.jdbc.ClientDriver</property> <mapping resource="contact.hbm.xml"/> </session-factory> </hibernate-configuration> hibernate.cfg.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"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="connection.username">classiccars</property> <property ame="connection.url">jdbc:derby://localhost:1527/myeclipse</property> <property name="dialect">org.hibernate.dialect.DerbyDialect</property> <property name="myeclipse.connection.profile">MyEclipse Derby</property> <property name="connection.password">myeclipse</property> <property name="connection.driver_class"> org.apache.derby.jdbc.ClientDriver</property> <mapping resource="contact.hbm.xml"/> </session-factory> </hibernate-configuration>
  • 25. http://www.java2all.com Step 9: -Now Create the First Persistence Class(java file). Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database  table so We can configure the variables to map to the database column. package com; public class Contact { private String firstName; private String lastName; private String email; private long id; public String getEmail() { return email; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public void setEmail(String string) { email = string; } public void setFirstName(String string) { firstName = string; } public void setLastName(String string) { lastName = string; } package com; public class Contact { private String firstName; private String lastName; private String email; private long id; public String getEmail() { return email; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public void setEmail(String string) { email = string; } public void setFirstName(String string) { firstName = string; } public void setLastName(String string) { lastName = string; }
  • 26. http://www.java2all.com public long getId() { return id; } public void setId( long l) { id = l; } } Step 10: Create the contact.hbm.xml file in a default package.
  • 27. http://www.java2all.com contact.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="com.Contact" table="APP.CONTACT"> <id name="id" type="long" column="ID" > <generator class="assigned"/> </id> <property name="firstName"> <column name="FIRSTNAME" /> </property> <property name="lastName"> <column name="LASTNAME"/> </property> <property name="email"> <column name="EMAIL"/> </property> </class> </hibernate-mapping> contact.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="com.Contact" table="APP.CONTACT"> <id name="id" type="long" column="ID" > <generator class="assigned"/> </id> <property name="firstName"> <column name="FIRSTNAME" /> </property> <property name="lastName"> <column name="LASTNAME"/> </property> <property name="email"> <column name="EMAIL"/> </property> </class> </hibernate-mapping>
  • 28. http://www.java2all.com package hibernate_demo; import java.util.Scanner; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.Contact; public class FirstExample { public static void main(String [] args) { Session session = null; try { SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); session =sessionFactory.openSession(); System.out.println( "Inserting Record…………"); Contact contact = new Contact(); Scanner s = new Scanner(System.in); System.out.println("Enter Id : "); int id = s.nextInt(); contact.setId(id); package hibernate_demo; import java.util.Scanner; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.Contact; public class FirstExample { public static void main(String [] args) { Session session = null; try { SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); session =sessionFactory.openSession(); System.out.println( "Inserting Record…………"); Contact contact = new Contact(); Scanner s = new Scanner(System.in); System.out.println("Enter Id : "); int id = s.nextInt(); contact.setId(id); Step 11: Now create the java file by which the data is inserting in  the table (CONTACT) at database.
  • 29. http://www.java2all.com System.out.println("Enter First name : "); String firstname = s.next(); contact.setFirstName(firstname); System.out.println("Enter Last name : "); String lastname = s.next(); contact.setLastName(lastname); System.out.println("Enter Email id : "); String email = s.next(); contact.setEmail(email); session.save(contact); System.out.println("Data inserted successfully………"); } catch(Exception e){ System.out.println(e.getMessage()); } finally { session.flush(); session.close(); } } }  System.out.println("Enter First name : "); String firstname = s.next(); contact.setFirstName(firstname); System.out.println("Enter Last name : "); String lastname = s.next(); contact.setLastName(lastname); System.out.println("Enter Email id : "); String email = s.next(); contact.setEmail(email); session.save(contact); System.out.println("Data inserted successfully………"); } catch(Exception e){ System.out.println(e.getMessage()); } finally { session.flush(); session.close(); } } } 
  • 32. http://www.java2all.com Console: log4j:WARN No appenders could be found for logger  (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly. Inserting Record………… Enter Id :  1 Enter First name :  java2all Enter Last name :  Learn Java Online Enter Email id :  contact@java2all.com Data inserted successfully……… This is a simple java hibernate example to insert a record in database.

Hinweis der Redaktion

  1. White Space Characters
  2. White Space Characters
  3. public long getId() { return id; } public void setId( long l) { id = l; } }
  4. public long getId() { return id; } public void setId( long l) { id = l; } }
  5. public long getId() { return id; } public void setId( long l) { id = l; } }
  6. public long getId() { return id; } public void setId( long l) { id = l; } }