Hibernate-1

1.INTRODUCTION

Java EE(Enterprise edition Java)
Simply EE focus to develop enterprise application development.The aim of the Java EE platform is to provide developers with a powerful set of APIs while shortening development time, reducing application complexity, and improving application performance.

Java EE vs Java SE

JDK(Java Development Kit)
    Java SE API
    JRE(JVM)
    Development Tools(Eg:-Javac,Serial version UID,etc)

Java EE based on java SE.In the java SE we can develop anything;Also EE application but that develop must concern cross cutting component.But in the Java EE developer can focus one develop the business logic,Lesley thinking about security,transaction,error handling,login etc.

JAVA SE gives a collection of specification(like documentation)+their implementation.
Java Terminologies_寒征男_新浪博客
JAVA SE gives  only specification.So several external companies implement that methods several ways
Eg:-Hibernate,Jetty,Apache Tom Cat,Glass fish

                    A summary of all Java EE specifications - Stack Overflow
Companies implement java EE specification in 2 ways

1.Implement all features in Java EE generally known ass Java EE Application Servers.
But the problem is application servers are hevy weight & low performnce. but the all out come of efferent application servers are as same as to the another application server.
Eg:-Glass Fish(Eplipse own)
       JBOss(WildFly0
       Oracle Web logic Servers
       TomEE

2.Implement part of Whloe Java EE
   (A) Web containers(JSP+Servlet+JSF)
        eg:-TomCat,Jetty(Spring boot default web container)
 
    (B)Implementation of JPA
        eg:-Hibernate,Eclipse Link,OpenJPA.

What is JPA
Simply JPA is the abstracted version of JDBC ,used to simplified & optimize time JDBC operations. 
As a specification, the Java Persistence API is concerned with persistence, which loosely means any mechanism by which Java objects outlive the application process that created them. 

in here,directly writing SQL query on Java File (i.e. directly to JDBC),which means more on the object model rather than on the actual SQL queries used to access data stores.Which Introduction
Object-Relational Mapping (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. use to map object relation.


What is ORM
Object-Relational Mapping (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm.So developers can code without big database knowledge.
Simply ORM defined as create a object for represent a entity.


Why we need JPA
JPA allows you to avoid writing DDL in a database specific dialect of SQL. Instead you write "mappings" in XML, or using Java annotations.
JPA allows you to avoid writing DML in the database specific dialect of SQL.
JPA allows you to load and save Java objects and graphs without any DML language at all.
When you do need to perform queries JPQL allows you to express the queries in terms of the Java entities rather than the (native) SQL tables and columns

What is Hybernate
Hibernate is the one of the popular implementation of the JPA.

Native Hybernate vs. JPA
Native Hibernate is based on Hibernate,which mean extended version of hibernate.but in the previous mention the artifact of all JPA implementations are equal but when we add Native hibernate method it do not works in another implementation.(Hibernate implementation do not works in eclipse link when use Native hibernate)

But when we download Hibernate,We will  get whole Native as  bundle as one.Developer have responsibility to use according to the Hibernate or Native hibernate.

2.Configuration & Start hibernate

Start hibernate
1-Enter Here to download Hibernate ORM & refer documentation:-https://hibernate.org/orm/

2-The you can download suitable stable  hibernate version according to your requirement.

3-extract it & go to inside hibernate-release-5.4.20.Final/lib/required & copy all  jar file inside that & copy them to your project lib file.Then go to project structure & import them when you using inteliJ
Eg:-antlr-2.7.7.jar
       byte-buddy-1.10.10.jar



4-If you use hibernate configuration using xml file you can add the hibernate.cfg.xml file via right side "+" mark.then confirm that using

Bootstrapping
There are 4 method start the framework(bootstrapping) in JPA.In here 2 for native hibernate & 2 for JPA-hibernate.
If we use JPA we can only acces for the JPA,but if we use Native Hibernate we can both use all JPA+Hibernate

(A)Native-Hibernate Bootstrapping    (B)JPA-Hibernate Bootstrapping
In here I use <session-factory> for bootstrapping ,then we can use both NH & JPA-H fetures.
<session-factory> used in native hibernate but <entity-manager-Factory> used in in JPA.
<session-factory> use for this framework & product of session factory is session this product is as same as functional to DBConnection in JDBC.

method-1-Get configuration from.xml file.


hibernate .cfg.xml

You can generate hibernate .cfg.xml from configuration.like....
  

But if you want you can manually do that creation of hibernate.cfg.xml file,You find the file from content form hibernate release(Zip),& you can copy that to your project.
path:-hibernaterelease5.4.20.Final/documentation/quickstart/html_single/hibernatetutorials/basic/src/test/resources/ibernate.cfg.xml

hibernate.cfg.xml

<!--prolog:indicate xml version+include Unicode characters can be present -->
<?xml version='1.0' encoding='utf-8'?>

<!--DOCTYPE: enable IDE can suggest hibernate syntax's-->
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration><!--root element-->
    <session-factory><!--Native hibernate configuration-->

<!--24.2Genaral configuration-->
<!--Hiberante can work with any DBMS,As a example I used MYSQL,As well as MYSQL has several version I used MYSQL 8,So dialect defined hibernate must write SQL queries as suitable to DBMS & its vesrion-->
        <property name= "hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>

<!--24.4Database connection properties-->
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">1234</property>

<!--24.10 Statement login & statistics -->
<!--View hibernate generated queries & format it to-->
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>

<!--24.15 Automatic Schema generation-->
<!--Mostly used in development environment,nor production envirnment-->
        <!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
    </session-factory>
</hibernate-configuration>

Generally these configuration are sufficient to development.

HibernateUtil.java
Session factory implements Factory design pattern & singleton design pattern in specific way for session factory. 
change the method of creation of session factory in hibernate version to version.
 public static SessionFactory buildSessionFactory() {
    /*content will change
    }
we can find that from

package lk.myorg.hibernate.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {

    private static SessionFactory sessionFactory = buildSessionFactory();

    public static SessionFactory buildSessionFactory() {
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .configure("/hibernate.cfg.xml")
                .build();

        Metadata metadata = new MetadataSources(standardRegistry)
                .getMetadataBuilder()
                .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE)
                .build();

        SessionFactory sessionFactory = metadata.getSessionFactoryBuilder()
                .build();
        return sessionFactory;
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

AppInizializer.java
package lk.myorg.hibernate.main;

import lk.myorg.hibernate.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class AppInizializser {
    public static void main(String[] args) {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        System.out.println(session);
        session.close();//After close session factory we cant create object from session factory
        sessionFactory.close();
    }
}


method-2-Get configuration property file file..(Recommended method)
In this method we use property file to store configuration. We can use this as internal resource ore external resource.

application.properties 

hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
hibernate.connection.url=jdbc:mysql://localhost:3306/mydb

#Create data base if the is no database called jpatest
hibernate.connection.url=jdbc:mysql://localhost:3306/jpatest?createDatabaseIfNotExist=true

hibernate.connection.driver_class=com.mysql.cj.jdbc.Driver
hibernate.connection.username=root
hibernate.connection.password=1234
hibernate.show_sql=true
hibernate.format_sql=true

#Extra configuration
#24.15. Automatic schema generation
#This must want to sync entity class with table
#
#Hibernate mapping to DDL

#none
#No action will be performed.

#create-only
#Database creation will be generated.

#drop
#Database dropping will be generated.(Drop when create the session factory)

#create
#drop tables in Db & create  tables
#Database dropping will be generated followed by database creation.

#create-drop
#Drop the schema and recreate it on SessionFactory startup. Additionally, drop the #schema on SessionFactory shutdown.

#validate
#Validate between the entity & database schema.

#update
#Update the database schema.No drop only apply db Changes.

hibernate.hbm2ddl.auto=update

changes in hibernateutil.java when use property file

Property file as Internal

application.properties file must be in the \src folder.

HibernateUtil.java

public class HibernateUtil {

    private static SessionFactory sessionFactory = buildSessionFactory();

    public static SessionFactory buildSessionFactory() {
       
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .loadProperties("application.properties")
                .build();

        Metadata metadata = new MetadataSources( standardRegistry )


                .getMetadataBuilder()
                .applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )
                .build();

        SessionFactory sessionFactory = metadata.getSessionFactoryBuilder()
                .build();
        return sessionFactory;

    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Property file as External Resource
HibernateUtil.java
public class HibernateUtil {

    private static SessionFactory sessionFactory = buildSessionFactory();

    public static SessionFactory buildSessionFactory() {
        File file = new File("resource/application.properties");
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .loadProperties(file)
                .build();

        Metadata metadata = new MetadataSources( standardRegistry )


                .getMetadataBuilder()
                .applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )
                .build();

        SessionFactory sessionFactory = metadata.getSessionFactoryBuilder()
                .build();
        return sessionFactory;

    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

In here we can  move to the application.properties to class path(point of JVM find the class:out side the module inside the project folder or custom class path)

3.Create databse using entity

In the JDBC we want to create a database in manually but in the the hibernate we can create entity for the represent database & hibernate automatically create database for our class.So ORM(Object relational Mapping),Class must inform fields are related to Data base.For that we use two methods.

1.xml configuration
2. Annotation(Mostly used in industry,further we refer this technique) 

Eg:-We can create separate packages for the entity class. 

Employee.java

package lk.myorg.hibernate.entity;

import javax.persistence.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

//Defined objects which will create using this class template are  entity
@Entity

//Table name explicitly match(Eg:If @Table(name="Managers") table name will be      // Manager,not Employee But generally we do not do that because it is Contradictory //to the DAO design pattern
@Table(name="Employee")

public class Employee implements Serializable {

    @Id
    @Column(name="id")  
    private int id;

    @Column(name="name")
    private String name;

    @Column(name="address")
    private String address;

    @Column(name="salary")
    private BigDecimal salary;

//we must use @Temporal in util.Date & util.Calendar.Because util/Date give the //date+time,but sql.Date this @ is not compulsory because it gives date only
    @Temporal(TemporalType.DATE)
    @Column(name="date_of_birth")
    private Date dob;

   //Minimum requirement to create table @Entity & @id,without other @ table will create without any error

    public Employee() {
    }

    public Employee(int id, String name, String address, BigDecimal salary, Date dob) {
        this.id = id;
        this.name = name;
        this.address = address;
        this.salary = salary;
        this.dob = dob;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public BigDecimal getSalary() {
        return salary;
    }

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }
    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", salary=" + salary +
                ", dob=" + dob +
                '}';
    }
}

In the hibernate wen want to inform session factory,what is the entity class.Ther are 2 methods to perform that
    1.through .xml file
        -.xml
        -using java code
    2.through .properties file
        -using java code

So I use the .properties file so we can use only the java code
HibernateUtil.java
public class HibernateUtil {

    private static SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory(){

        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .loadProperties("application.properties")
                .build();

        Metadata metadata = new MetadataSources( standardRegistry )
                .addAnnotatedClass(Employee.class)
                .addAnnotatedClass(Student.class)
                .getMetadataBuilder()
                .applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )
                .build();

        SessionFactory sessionFactory = metadata.getSessionFactoryBuilder()
                .build();

        return sessionFactory;
    }

    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }

}

5.Crud Operations

In the hibernate for creation purposes,There is standard to use transactions. 

HibernateUtil.java
public class HibernateUtil {
    public static void main(String[] args) {

        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();

        Transaction tx = session.beginTransaction();//start transaction
        //Execution code context
        tx.commit();//commit the transaction
    
        session.close();
        sf.close();
    }
}
(NH-native hibernate,JPAH-Java persistence language application protocal interface hibernate)

(A)save(NH) VS persist(JPAH)

save-return type Serializable->Return  primery key of entity
persist-return type void

save(entity)
persist(entity)

(A)delete(NH) VS remove(JPAH)
Mechanism:
1-Check availability of row using select query
2-If it exists, delete the row,else if print empty select query without any exception.

delete(entity)
remove(entity)
 @id is sufficient for deletion.






























Comments

Popular posts from this blog

Hibernate-2

Avoid Round-off error in large & Small numbers using BigDecimal Class in Java