02. ORM - Hibernate

HIBERNATE

ORM පිලිබදව ලියා ඇති blog එක බලලා hibernate පිලිබදව ඇති මෙම blog එක read කරන්න.

ORM concept එක implement කර ඇති technology වල ranking වලට උඩින්න්ම පවතින්නේ hibernate (simply hibernate maps object world with relational world).

Eclipse වලදී අප develop  කරන විවිද application  වල්දී බාවිතා වන technology එක තවත් පහසුවෙන් හැසිරවීමට plugging add  කරගන්න පුළුවන්.උදාහරණයක් ලෙස hibernate  බවිතා කරන විට plugging add  කිරීම බලමු.මේදී උදාහරණයක් ලෙස database එක හා සම්බන්ද  configuration  අපිට කරන්න වෙනවා(database එක මොකද්ද, මොකද්ද බාවිතා කරන driver එක, username password මොනවද වගේ විස්තර අපි දෙන්න ඕනේ).මේක අපි manually code කරන්න යන්නේ නැතිව plugging එකක් දාගත්තම ලේසියෙන් කරගන්න පුළුවන්.

How to add hibernate plugging

Go to , Help – eclipse marketplace - search hibernate and then install JBoss Tools




 

 

 

 

Adding database configuration file as XML file

Right click on the project – new – other – search hibernate and select Hibernate Configuration File(cfg.xml) – next – then file can be change or not (if it is change that name should be manually provided  in the place where hibernate configuration file name should be provided. It also explain bellow) – next provide related information and finish.

ඒසේ සදෙන XML file එකේ default name එක hibernate.cfg.xml වේ.නමුත් අප custom file name  එකක් යොදාගන්නේ නම් (eg: hibernateConfigure.cfg.xml ) ඒ නම පහත පරිදි code එක තුලදී ලබදිය යුතුය.

Configuration con = new Configuration().configure(“hibernateConfigure.cfg.xml “);

නමුත් default name  එක බාවිතා වන්නේ නම් code එක තුලදී  ඒ නම සදහන් කිරීම අවශ්‍යම නොවේ.

Configuration con = new Configuration().configure();




Hibernate.cfg.xml FILE

////////////////////////////////////////////////////////////////////////////////////////

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

               "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

               "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

 

<hibernate-configuration>

   <session-factory>

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

<property name="hibernate.connection.password">root</property>

<property name="hibernate.connection.url">

jdbc:mysql://localhost:3306/JerseyRestCompay

</property>

<property name="hibernate.connection.username">root</property>

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

 

<property name="hbm2ddl.auto">update</property>

<property name="show_sql">true</property>

 

  </session-factory>

</hibernate-configuration>

////////////////////////////////////////////////////////////////////////////////////////

 

<property name="hbm2ddl.auto">update</property> 

This tells whether data base table should be newly created or update existing tables.


Java class කලින් හදාගෙන ඊටපස්සේ ඒ class වලින් database එකේ table හැදෙන්න ඕනෙනම් පලවෙනි පර project එක run කරද්දී create ලෙස තිබියවේ.මෙවිට database එකේ අලුතෙන් table සදගනී.උදාහරණයක් ලෙස Employee entity class එක අපි java වල හදල එකකට employee කියලා table එකක් database හදාගන්න ඕනෙනම් create ලෙස තිබ්බම අලුතෙන් එකක් සාදාගනී.employee කියලා table එකක් තිබ්බොත් එක delete කරලා යේ අලුතෙන් එකක් සදයි.නමුත් update ලෙස තිබ්බම වෙන්නේ database එකේemployee කියලා table එකක් තියනවනම් එක update වෙන එකියි.එහෙම table එකක් නැත්තම් එක error එකක් ලෙස එනවා.


<property name="show_sql">true</property> 

අපි hibernate වලදී බාවිතා කරන්නේ HQL හෙවත් hibernate query language වේ.නමුත් hibernate වලදී එය SQL වලට convert කරවාගෙන තමා database hit වීම වෙන්නේ.එහිදී අපිට අප දෙන HQL එකට අදාළ SQL  එක බලාගන්න ඕනෙනම්, ඉහත පරිදී (Hibernate.cfg.xml තුල) දෙන්න ඔනී.මෙවිට HQL  වලට අදාළ SQL query console එකේ බලාගත හැක.

 

 

 

 

 

 

Entity Cass (Model Class)

Database වල table, අපේ application එක තුල represent කරගන්න හදන class එකක් සරලව entity class එකක්’ කියනවා.උදාහරණයක් විදිහට student කියන database table එක application එක තුලදී represent කරගන්න Student.java Class හදනවා.

 

Student table – student_id (primary Key), student_name

විදිහට employee_data කියන database table එක application එක තුලදී represent කරගන්න 

Employee.java Class හදනවා.

@Entity
Public class EmployStudent{

@Id
Private int student_id ;
private String student_name;

publicint getStudent_id() {
returnstudent_id;
}

publicvoid setStudent_id(intstudent_id) {
this.student_id = student_id;
}

public String getStudent_name() {
returnstudent_name;
}

publicvoid setStudent_name(String student_name) {
this.student_name = student_name;
}
}

 

......................................................................................................................................................................

employee_data table - empId (primary Key,auto increment) , emp_name

 

@Entity
@Table(name="employee_data")
publicclass Employee {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // auto increment field
privateintempId;
private String emp_name;

publicint getEmpId() {
returnempId;
}

publicvoid setEmpId(intempId) {
this.empId = empId;
}

public String getEmp_name() {
returnemp_name;
}

publicvoid setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
}

මෙහිදී class එකේ attributes මගින් database table එකේ column represent කරයි.එක java object එකක් මගින් table එකේ row එකක් නිරුපනය කරයි.Employee object එකක් යනු එක Employee කෙනෙක්.එනම් database table එකේ එක row එකක්.

Entity class වල බාවිතා වන annotations

@Entity

Public class Employee{}

මෙය අනිවාර්ය වන අතර එම  class එක entity class එකක් බව කියවී.මෙවිට් class name එක database table එකේ name එකම වී.තවද HQL query වලදී class name එක යොදාගත යුතුවේ.(class එකEmployee.java නම්).hql query for selecting all data from employee data table – “from Employee”;

 

@Entity(name="employee_data")

Public class Employee{} 

මෙවිට් class name එක database table එකේ name එකම වනොවන අතර database table name එක වේ.තවද HQL query වලදී employee_data  යන name එක යොදාගත යුතුවේ.hql query for selecting all data from employee data table – “from employee_data”;

 

@Entity(name="employee_data")

මෙහිදී එකමදෙය නම් database table name එක class name එක නොවී employee_data  වේ..තවද HQL query වලදී class name එක යොදාගත යුතුවේ.(class එකEmployee.java නම්).hql query for selecting all data from employee data table – “from Employee”;

 

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY) // auto increment field

Private int d_code;

d_code යනු database table එකේ primary key එක වන අතර (@Id) එය auto increment එකක් වේ(@GeneratedValue(strategy = GenerationType.IDENTITY)).

 

@Transient

private String department_head; 

department_head - මෙය database table එකේ column එකක් නොවේ.


@Embeddable

Public class DepAddress {}

මෙම class එක එය බාවිතා කරන අනෙක් entity class වලට embed වෙලා තියෙන්නේ.පහත උදාහරණය බලන්න.

 

@Embeddable

Public class DepAddress {

String frist_line;

      String second_line;

      String third_line;

}

 

@Entity

publicclass Department {

      @Id

      privateintd_code;

      private DepAddress address;

 

}

 

 

Department class එකට අදාළ database table එකේDepAddress හි attributes වලට අදාල columnsadd වේලා තියෙන්නේ.table එක පහත පරිදි වේ.

Department table එක -(d_code, frist_line, second_line, third_line)

 

@OneToOne
@OneToMany
@ManyToOne
@ManyToMany

 

පාසලක student සහ book සලකා බලමු. 

එක ළමයෙකුට පොත් එකයි සහ එක පොතක් අදාළ වෙන්නේ එක ළමයෙකුට විතරයි - @OneToOne

එක ළමයෙකුට පොත් ගොඩක් තිබිය හැක නමුත් එක පොතක් අදාළ වෙන්නේ එක ළමයෙකුට විතරයි - @OneToMany

එක ළමයෙකුට පොත් එකයි නමුත් එක පොතක්  ළමයි ගොඩකට අයිති වේ - @ManyToOne

එක ළමයෙකුට පොත් ගොඩක් තිබිය හැක සහ එක පොතක්  ළමයි ගොඩකට අයිති වේ. - @ManyToMany

 

 

@OneToOne


 

@OneToMany AND @ManyToOne 

--------------------------- Without mapped by --------------------------


------------------------------With mapped by -------------------------------


@ManyToMany

--------------------------- Without mapped by --------------------------

 


@ManyToMany

---------------------------With mapped by ---------------------------------

 


@Cacheable

@Cache(usage = CacheConcurrencyStrategy.NONE)

@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)

@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)

@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)

 

 

 

 

@Entity

@Cacheable

@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)

publicclass Employee {}

Cache පිලිබදව පහත විස්තර කරනු ලබයි.


---------------------------------------     Hibernate cache       --------------------------------------

අප කරන විවිද වැඩ වල results තාවකාලික memory වල තියාගන්නවා.ඒ ඇයි, අප කලින් කල වැඩක් නැවත කරලා data ටිකක් ගන්න ඕනෙනම්, data තියන original source එකට ගහින් data අරන් එනවට වඩා පහසුයි අර තාවකාලික memory වලින් අරන් data ටික එවන එක(effective).මොකදඒ data ටික අපි කලින් ගත්ත නිසා අයෙත් original source  එකට ගිහින්ම data ගෙනවිත් දීම effective වැඩක් නෙවෙයි.උදාහරණයක් ලෙස browser එකේ cache ගැන හිතමු.අපි මොකක් හරි data ටිකක් internet එකෙන් ගත්තට පස්සේ, අයෙත් ඒ data ටිකමනම් ඔනේ අයෙටත් internet එකෙට ගහින් ගෙන එකට වැඩා ලේසි browser එකේ cache වලින් ඒක ගන්න එක.අපි තවත් විදිහකට බලමු, මට ඔනී america වල ඉන්න uncle ගෙන් එයාගේ වයස අහන්න.ඉතින් එක මම call කරලා වයස අහගෙන අම්මට කියනවා.අම්මටත් එක මතාක තියන් ඉන්නේ.එත් අයෙත් ටික කාලෙකින් මට එක අමතක වෙලා අයෙත් දැනගන්න අවශ්‍ය වෙනවා.එකට හොදම වැඩේ තමා මුලින්ම ලගම ඉන්න අම්මගෙන් අහල එක දනගන්න එක.මොකද අම්මට එක මතක නිසා.නැත්තන් ආයෙමත් america ඉන්න ඒ unclecall කරන්න වෙනවා.එක අමතරව කරන්න ඕනේ බොරුව වැඩක්. මොකද අම්ම දනනවා එක.එයාගෙන් අහන එක තම effective .

hibernate වලදී මෙහෙමයි වෙන්නේ.අපි මොකක් හරි query එකක් ගහල database එක hit කරලා data ටිකක් ගණන්වා.ඊට පස්සේ ඒ ගත්ත data ටික hibernate cache වල තියන් ඉන්නවා.අයෙත් ඒ data ටිකම ඕනේ උනාම hibernate වලින් මොකද කරන්නේ, database hit එකක් නොකර cache වලින් ඒ data ටික අර දෙනවා.hibernate වල බාවිතා වන cache වර්ග 2ක් තිබෙනවා.

01. First level cache. (Default, this is enable)

02. Second level cache. (If we want do use this, we have to do some configurations)

First level cache දී එක user session එකකට අදාල data පමණක් cache එකේ තබා ගනී.Second level cacheදී user session එකක් හෝ එකකට වඩා වැඩි ප්‍රමාණයකට අදාල data, cache එකේ තබා ගනී.

කොච්චර session එකම application  එකට තිබ්බත් Second level cache  දී ප්‍රශ්නයක් වෙන්නේ නෑ.ඔක්කොම session වලට Second level cache එක share කර ගන්න පුළුවන්.නමුත් First level cache (hibernate default provide it) එක session එකකට විතරයි.


 


Hibernate default first level cache provide කරන අතර second level cache එක use කරන්න ඕනේ නම් thirty party library බාවිතා කරන්න වෙනවා.ඒවා නම්,

1.      Ehcache

2.      OS

3.      Swam

මෙම thirty party library බාවිතා second level cache එක use කර ගන්න නම් application එක configure කරගන්න ඕනේ වෙනවා.

 

Steps

Ehcache – this will provide the features

hibernate-ehcache – this will provide integration hibernate and ehchach

01.   Configure pom.xml.

Goto pom.xml and add ehcache (in the dependency, search ehcache and install org.hibernate version should be same equal to hibernate version)



 



 



 

 

 

02.   Configure hibernate.cfg.xml – to enable second level chache,by default it is disabled.

03.   Configuring the Entity class – By default every entity is not cacheble.In here basically two annotation is used.

@Cachable – This entity is eligible for chaching.

@Chache – to provide strategy (read only , …)

 

 

Implementation - 1st level cache

 

1st level cache සහ session එකක් ද නිසා database වෙන්න් එක පාරයි.

Session session = sf.openSession();
Transaction tx = session.beginTransaction();

System.out.println("----------------------Using 1 session------------------------------------");
Employee emp = (Employee) session.get(Employee.class, 1);
System.out.println(emp);

Employee emp = (Employee) session.get(Employee.class, 1);
System.out.println(emp);

tx.commit();
session.close();


1st level cache සහ session දෙකක් ද නිසා database එක ද දෙපාරක් hit වී ඇත.

System.out.println("----------------------Using 2 sessions------------------------------------");
Session session1 = sf.openSession();
Transaction tx1 = session.beginTransaction();
Employee emp = (Employee) session.get(Employee.class, 1);
System.out.println(emp);
tx1.commit();
session1.close();

Session session2 = sf.openSession();
Transaction tx2 = session.beginTransaction();
Employee emp = (Employee) session.get(Employee.class, 1);
System.out.println(emp);
tx2.commit();
session2.close();

 


Implementation 2nd  level cache 

-----------------------------------------------------------------------------------------------------------------------------

 


public static Session sessionBulder(){
        Configuration con = new Configuration().configure().addAnnotatedClass(Category.class);
        ServiceRegistry reg = new ServiceRegistryBuilder().applySettings(con.getProperties()).buildServiceRegistry();
        SessionFactory sf = con.buildSessionFactory(reg);
        Session session = sf.openSession();
        return session;
    }
    
    
    public void n(){
        Session session = CategoryDAOImpl.sessionBulder();
        //INSERT NEW CATEGORY
        Category c = new Category();
        c.setActive(true);
        c.setDescription("description");
        c.setImageURL("imageURL");
        c.setName("name");
        
        Transaction tx = session.beginTransaction();
        session.save(c);
        //session.persist(c);
        
        ///////////////////////////////
        
        //UPDATE CATEGORY
        Transaction tx = session.beginTransaction();
        Query query = session.createQuery("from Category where id = ?");
    query.setParameter(0, 6);
        /*Query query = session.createQuery("from Category where id = :b");
    query.setParameter("b", 4);*/
    
     Category c = (Category)query.uniqueResult();
        c.setImageURL("imageURL_2");
        session.update(c);
        
        //////////////////////////////////
        
        //DELETE CATEGORY
    
    
     Transaction tx = session.beginTransaction();
        Query query = session.createQuery("from Category where id = ?");
    query.setParameter(0, 6);
     Category c = (Category)query.uniqueResult();
     session.delete(c);
        
        session.getTransaction().commit();
        session.close();
        
        
        
        
         /*Session session = HotelDaoImpl.sessionBulder();
     Query query = session.createQuery("from Hotels where city_code = ?");
    query.setParameter(0, city_code);
     List list = query.list();*/
        
        
    }

 

 





Comments

Popular posts from this blog

09.Data Binding.

Database - Topics

02. Spring – Creating spring project clone it with GIT step by step.