Hibernate was started in 2001 by Gavin King as an alternative to using EJB2-style entity beans. Its mission back then was to simply offer better persistence capabilities than offered by EJB2 by simplifying the complexities and allowing for missing features.
Hibernate used its mapping files and configuration files to achieve its objectives. With the introduction of annotations in java community with JDK 1.5, Hibernate community started working on Hibernate 3, which had support for annotations. The current version of hibernate is hibernate 5.
In this hibernate example with annotations, we will learn more information on hibernate and step by step build our first running example application for beginners.
What is hibernate
Hibernate is an open source object relational mapping tool for Java. It provides a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC.
Mapping Java classes to database tables is accomplished through the configuration of an XML file or by using Java annotations. There are facilities to arrange one-to-many and many-to-manyrelationships between classes are provided.
In addition to managing associations between objects, Hibernate can also manage reflexive associations where an object has a one-to-many relationship with other instances of its own type.
How hibernate works
Hibernate doesn’t get in our way; nor does it force us to change the way our objects behave. The objects don’t need to implement any magical interfaces in order to be blessed with the ability to persist. All we have to do to put some meta data in form of annotations telling hibernate that how to use them when mapping them with database. At runtime, hibernate reads these annotations and use this information to build queries to send to some relational database.
There is a simple, intuitive API in Hibernate to perform queries against the objects represented by the database, to change those objects we just interact with them normally in the program, and then tell Hibernate to save the changes. Creating new objects is similarly simple; we just create them in the normal way and tell Hibernate about them using annotations so they can get stored to the database.
Relation of hibernate with JPA
JPA (Java Persistence API) is an specification for persistence providers to implement. Hibernate is one such implementation of JPA specification. We can annotate our classes as much as we would like with JPA annotations, however without an implementation nothing will happen.
Think of JPA as the guidelines/specification that must be followed or an interface, while Hibernates JPA implementation is code that meets the API as defined by JPA and provides the under the hood functionality.
When we use hibernate with JPA we are actually using the Hibernate JPA implementation. The benefit of this is that we can swap out hibernates implementation of JPA for another implementation of the JPA specification.
When we use straight hibernate your locking into the implementation because other ORMs may use different methods/configurations and annotations, therefore we cannot just switch over to another ORM.
Java Hibernate hello world example
Lets create our step by step hibernate hello world example. In this example, I have created an
Employee
class and declared four attributes id
, email
, firstname
and lastname
.
I want the
id
attribute should be generated automatically so that application code does not store a local cache of employee ids.
So far we targeted what we want to make in our first application. Lets identify the files need to be created.
- hibernate.cfg.xml -This configuration file will be used to store database connection information and schema level settings.
- EmployeeEntity.java – This class will refer Java POJOs having hibernate annotations.
- HibernateUtil.java – This class will have utility methods which will be used for creating session factory and session objects.
- TestHibernate.java – This class will be used to test our configuration settings and Emplyee entity annotations.
Before moving into code, lets see the project setup and adding maven dependencies which need to added to
pom.xml
to include all compile time and runtime dependencies.1. Create a maven project
2. Make project to support eclipse
3. Import java project to eclipse workspace
Above steps will create the minimum setup. Now its time to add hibernate dependencies.
4. Hibernate Maven Dependencies
< dependency > < groupid >org.hibernate</ groupid > < artifactid >hibernate-commons-annotations</ artifactid > < version >3.0.0.ga</ version > </ dependency > < dependency > < groupid >org.hibernate</ groupid > < artifactid >hibernate-annotations</ artifactid > < version >3.3.0.ga</ version > </ dependency > < dependency > < groupid >mysql</ groupid > < artifactid >mysql-connector-java</ artifactid > < version >5.1.6</ version > </ dependency > < dependency > < groupid >antlr</ groupid > < artifactid >antlr</ artifactid > < version >2.7.6</ version > </ dependency > < dependency > < groupid >commons-collections</ groupid > < artifactid >commons-collections</ artifactid > < version >3.1</ version > </ dependency > < dependency > < groupid >dom4j</ groupid > < artifactid >dom4j</ artifactid > < version >1.6.1</ version > </ dependency > < dependency > < groupid >javassist</ groupid > < artifactid >javassist</ artifactid > < version >3.4.GA</ version > </ dependency > < dependency > < groupid >javax.transaction</ groupid > < artifactid >jta</ artifactid > < version >1.1</ version > </ dependency > < dependency > < groupid >org.slf4j</ groupid > < artifactid >slf4j-api</ artifactid > < version >1.5.6</ version > </ dependency > < dependency > < groupid >org.slf4j</ groupid > < artifactid >slf4j-log4j12</ artifactid > < version >1.5.6</ version > </ dependency > |
Please note that we are not using all maven dependencies in this hibernate example but they will be used when we start expanding our application.
5. Hibernate Configuration
<? xml version = "1.0" encoding = "utf-8" ?> <! DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" < hibernate-configuration > < session-factory > < property name = "hibernate.connection.driver_class" >com.mysql.jdbc.Driver</ property > < property name = "hibernate.connection.password" >lg225295</ property > < property name = "hibernate.connection.username" >root</ property > < property name = "hibernate.dialect" >org.hibernate.dialect.MySQLDialect</ property > < property name = "show_sql" >true</ property > < property name = "hbm2ddl.auto" >update</ property > < mapping class = "hibernate.test.dto.EmployeeEntity" ></ mapping > </ session-factory > </ hibernate-configuration > |
Do not forget to set correct password before running this hibernate example.
6. Hibernate entity class
package hibernate.test.dto; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.hibernate.annotations.OptimisticLockType; @Entity @org .hibernate.annotations.Entity(optimisticLock = OptimisticLockType.ALL) @Table (name = "Employee" , uniqueConstraints = { @UniqueConstraint (columnNames = "ID" ), @UniqueConstraint (columnNames = "EMAIL" ) }) public class EmployeeEntity implements Serializable { private static final long serialVersionUID = -1798070786993154676L; @Id @GeneratedValue (strategy = GenerationType.IDENTITY) @Column (name = "ID" , unique = true , nullable = false ) private Integer employeeId; @Column (name = "EMAIL" , unique = true , nullable = false , length = 100 ) private String email; @Column (name = "FIRST_NAME" , unique = false , nullable = false , length = 100 ) private String firstName; @Column (name = "LAST_NAME" , unique = false , nullable = false , length = 100 ) private String lastName; // Accessors and mutators for all four fields } |
7. Hibernate session factory
package hibernate.test; import java.io.File; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new AnnotationConfiguration().configure( new File( "hibernate.cgf.xml" )).buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println( "Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { // Close caches and connection pools getSessionFactory().close(); } } |
Please do not forget to use the correct path of
hibernate.cgf.xml
.8. Demo
package hibernate.test; import hibernate.test.dto.EmployeeEntity; import org.hibernate.Session; public class TestHibernate { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); // Add new Employee object EmployeeEntity emp = new EmployeeEntity(); emp.setEmail( "demo-user@mail.com" ); emp.setFirstName( "demo" ); emp.setLastName( "user" ); session.save(emp); session.getTransaction().commit(); HibernateUtil.shutdown(); } } |
Above code will create a new table employee in database and insert one row in this table. In logs you can verify the insert statement which got executed.
Hibernate: insert into Employee (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?) |
If you face problem in running above hibernate hello world example, drop me a comment and I will be glad to discuss the problem with you.
No comments:
Post a Comment