Introduction to hibernate and JPA (Hibernate) setup (configuration)

We first need to talk about the limitations of the JDBC.
All we know about JDBC is that to connect to the database by manually giving the queries.
To list out the limitations in a simple way here is the following:

Only three points as per the concept here but if we go in detail we'll get clarity as
  1. Maintenence
  2. Performance
  3. Productivity
Main disadvantages of JDBC.
  • Once we write the query it should run in all the databases that is meant for maintenance disadvantage of JDBC.
  • We need to learn SQL.
  • Code must be maintained all through the application.
  • Performance may be missing due to lack of knowledge in the database queries for the end user.
  • Application development will not be in a rapid stage.

Hibernate is used to map java class definition with database table definition.
databasetable
Steps to work with hibernate:
  • create a simple maven project
  • Create either .jsp or .html file according to the application in which format you desired to display.

JPA (Hibernate) Configurations:

Maven dependences:

We need dependencies for anything (i.e) hibernate, mysql etc..., jar is must. Next is "what dependencies should be added for hibernate".
We should add dependencies to the pom.xml,
  • driver jar like mysql-connector-java.
  • hibernate-jpa-2.0-api
  • hibernate-entitymanager
No need to worry about getting the dependencies, just go to Google and search for hibernate maven dependencies.
Just copy the code of dependencies and paste it in the pom.xml, then maven will download all the jars and add to the eclipse build path.
Add the required dependences in pom.xml. In pom.xml to add the project dependences shown below:
						
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.gk</groupid> <artifactId>Geeklabs</artifactId> <packaging>war</packaging> <Version>0.0.1-SNAPSHOT</Version> <name>Geeklabs Maven Webapp</name> <url>http://maven.apache.org<url> <dependencies> <dependency> <groupid>javax.servlet</groupid> <artifactId>servlet-api</artifactId> <Version>2.4</Version> <Scope>provided</Scope> </dependency> <dependency> <groupid>mysql</groupid> <artifactId>mysql-connector-java</artifactId> <Version>5.1.14</Version> <Scope>compile</Scope> </dependency> <dependency> <groupid>org.hibernate.javax.persistence</groupid> <artifactId>hibernate-jpa-2.0-api</artifactId> <Version>1.0.0.Final</Version> </dependency> <dependency> <groupid>org.hibernate</groupid> <artifactId>hibernate-entitymanager</artifactId> <Version>3.6.5.Final</Version> </dependency> </dependencies> <build> <finalname>GeekLabs</finalname> <plugins> <plugin> <groupid&org.apache.maven.plugins</groupid> <artifactId>maven-eclipse-plugin</artifactId> <Version>2.9</Version> <configuration> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> <wtpversion>1.5</wtpversion> </configuration> <plugin> <plugins> <build> </project>
persistence.xml:
In project, under MET-INF folder, create the persistence.xml.All pojo classes (classes which marked with @Entity) are written in the persistence.xml. The src/main/java folder contains the java programs and the resources folder contains META-INF folder that contain persistence.xml. file. JPA expects some information that is kept in specified file called persistance.xml which must be placed in META-INF folder in src/main/resources.

In persistence.xml having the <persistence-unit name="geeklabs">, this unit name will be used to configure Ejb3Configuration instance.
						
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="geeklabs" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>com.gk.pojoclass.Admin</class> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect .MySQLDialect"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> <property name = "hibernate.hbm2ddl.auto" value = "update"/> </properties> </persistence-unit> </persistence>
<property name="hibernate. Dialect" value="org.hibernate dialect.mysqlDialect" /> In this property tag, property value with the name of the db to which we are connecting. These all information from persistent.xml will be read by hibernate at runtime, and based on this information hibernate behaves at runtime. This is very important to understand that the queries are generated by hibernate by reading the dialects in the persistence.XML file during runtime.
The structure of the hibernate must be in the below format: Pojo Classes (plain Old Java Object):
Here shown the simple pojo class. You should not forget to mark each hibernate entity class with @Entity annotation and add this class fully qualified name in the persistent.xml. For instance add this class as com.gk.pojoclass.Admin
						
package com.gk.pojoclass; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table (name = "admin") public class Admin { @Id @GeneratedValue private long id; @Column private String uname; private String pwd; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUname() { return uname; } public void setUname(String username) { this.uname = username; } public String getPwd() { return pwd; } public void setPwd(String password) { this.pwd = password; } }
Now we are going for annotation that is nothing but the POJO classes.
Mapping information is provided by JPA annotations between java program and table in the Database. JPA ORM annotations come from JPA library. The entities are of some list like @Entity,@Table, @Id, @GeneratedValue, etc…
  • @Entity is must in the class this is because to make the class as hibernate we use @Entity annotation so this is must in the hibernate POJO class.
  • @Table(name="Admin") this annotation is optional because if don't mention the name then by default the class name is taken as Table name.
  • To specify our field or column as primary key then mention @Id for the field.
  • @GeneratedValue is used to auto increment the value of field in the table.
The class name is 'Admin'. As we said before we should add this class to the persistence.xml file. The POJO class named Admin.

EMF (Entity Manager Factory):

In general to create EMF, good idea is to follow the ‘Single pattern’. For simplicity purpose jpa configuration details are hardcoded in below class, actually you should get them from outside.
Note: persistence unit name must match with the configure method in our entitymanager class as shown above.

To work out with this, first we need to create instance for EJb3Configuration class.Ejb3Configuration class is used to configure jpa from persistence.xml by using 'persistence unit' name
						
package com.gk.model; import java.util.HashMap; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.hibernate.ejb.Ejb3Configuration; public enum EntityManagerProvider { INSTANCE; private EntityManagerFactory entityManagerFactory; private EntityManager entityManager; private EntityManagerProvider() { Ejb3Configuration cfg = new Ejb3Configuration(); Ejb3Configuration configured = cfg.configure("geeklabs",getConfigurationMap()); entityManagerFactory = configured.buildEntityManagerFactory(); entityManager = entityManagerFactory.createEntityManager(); } public EntityManager getEntityManager() { return entityManager; } private Map<String , Object> getConfigurationMap() { Map<String , Object> CofigOverrides=new HashMap<String , Object>(); CofigOverrides.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); CofigOverrides.put("javax.persistence.jdbc.user", "root"); CofigOverrides.put("javax.persistence.jdbc.password", "root"); CofigOverrides.put("javax.persistence.jdbc.url","jdbc:mysql://localhost:3306/geeklabs"); return CofigOverrides; } }
Instance for Ejb3Configuration class.

The other way to give our information (i.e) the database connection details is by creating key/value pair that is by using Hash Map.

Adding driver, user, password and url. The Map instance is given to the configure (). This is the place where all the connection details are present.
The above code shows the details that are in getConfigurationMap() which is given as instance in the configure() as shown above.

→ Next we need to create instance for buildEntityManagerFactory.
 
entityManagerFactory=configured.buildEntitymanagerFactory();
→ create instance for createEntityManagerFactory.
					
entityManager=entityManage.createEntitymanagerFactory();
EntityManager instance must be only one. It must be closed after the application is closed.

EntityManager instance is just like the st.executeUpdate in JDBC.
HTML Comment Box is loading comments...