Saturday, December 15, 2012

How to setup Hibernet in the windows

downloads the .jar file from the hibernet site.Download and extract the zip file u can see 
java folder..open it...
u can seee hibernet3.jar file
also u can see lib folder also from extracted folser which contains library file which are want to execute the hibernet.

Now create a new project with eclips.
\right click on project and go properties--->java build path--->Libraries
click on Add Library
select User Library
Next
Again User Library
New
Give a name for New User Library
Dont make a tik for System library
click Ok
Now u can see created Hibernet Library...
Now u wanna add required jars to this library
click on add jars
select jars u wanna add and Ok
hibernet.jar
libraries inside requied folder and lib folder
javaassist.jar
and otehr libries if u want can add
and click Ok
now u can see Hibernet library
tik on the box and Finish..
Now u can see added library in the project explorer
U finish the hibernet configuration.................
............................................
(Hibernet internally using JDBC to connect to the database)

if u not using hibernet for saving data .................................................
1. we hv to use JDBC configuration
2.we hv to write model objdriver
3.service method to create a the model object
4.db design
DAO method to save the object using SQL

if u use hb
1.JDBS configuration using by HB configuration file
2.The model object using annotation
3. service method to create a the model object using HB API
4.others no need

-----------------------------------------------------------------------------------------------------
create hb config file...
Right click on project  and New....>File
Give the name as  hibernet.ctg.xml and save it in the src folder of the projects
Open the file..its blank..
write the code for configuration file there..
In ur downloaded file , hv a folder a project..inside this folder hv lots of sample configuration files ...
just open a one and edite a sample config file
give the database details to the xml file
give the dialect class name
Dialect--what kind of languges need  to use to writing the SQL queries by the hibernet for accesssing database.
u can find thei from libraries ....
u hv to mention all the entity classes with Name the annotated entity tag

Optianal --------------
u can giv show sql as true., then hb will save all the quires create to, access the database
u can giv the hmb2ddl.auto to create the  table if the table is not there it will create the auto.

-------------------------------------------------------------------------
now create a entity class
 HOW TO CREATE A ENTITY CLASS
to mention as a class use Entity --(we telling to Hibernet that this class is a Entity class)
to mention the primary key use Id


create sessionFactory object
then can create sessions from session factory object when database transaction happening


Wednesday, December 12, 2012

Hibernet Basics

Hibernet is a ORM tool
Hibernet used in data layer of application
Hibernet implenet JPA

y we use Hibernet?
we hv to persist(save) data to a db.
we want to save object(in java) data in a table(in db)
hv to map objects to tables for this.
map variable to columns.
map relatioships(foriegn key,primary key).
map data types.
managing changes to object state.

Hibernet is objects---Relationals-Mapping(ORM) tool

we want to tell to hibernet database details(host/uname/passwd)
want to tell to hibernet what are the objects want to save(for this use anotations)
we want to create a method to create a model object instance.(do this by Hibernet API)


Hibernet API tasts folowing...........

want to create session factory obj
then we can create sessions from session factory class
for each data base transaction(save/retreive/edit/delete/) hv to use one session object
for create a SF , we want to use configauration class and methods..
using sessionFactory we can create session objects..this session obj we want to use for db tranascations.......

EX-
UserDetails class
hibernet configuration class
Main class

using these we can send data to the database------

we can control the data format some way by using anotations like @Temperal,@Lob ,@Basic(),@etc..

using session obj we can send data to db
using session obj we can get data from db

Sunday, December 9, 2012

just still my note


Let the customer talk--find what the system needs to Do...(later can think how the system will do)
U need to imagin and relised how the system actually work to get better requirements..
Ask the questions to identify actually what they need..,.........
want to imagin by listing the steps for each tasks one by one.......

1. List out the steps for a task(for one task may be 7 steps to complete the task)
2. Write down the ALTERNATE PATHS for each steps which may be affect for that task
3.

Use cases
Use case is what the system does to accomplish agoal...
List of steps that the system has to do work correctly...
usecase is for specially accomplishing one perticular goal...
For each goal required seperate use cases..

We can easily realise soround stuffs of task by creating use cases(Ex-door want to close automatically)...therwise never can it properly..
We can use use cases for explain the system to customer or Boss...
want to maintain as simple with everyday language..


Use cases
1. Every use case must have a clear value to the system(mean usecase help to the achive the goals)
2. Every use case must have definite starting and ending point..
3. Every use case have a external initiator...it may be out side the system.


Ex-
1. clear value - Todd at the bed, dog out side the .....no warries...
2. External Initiator-dog barks for to be let out
3. stoping point -The door shut automatically

AFTER WANT TO CHECK REQUIREMENT LIST AND USE CASES TO CHECK WHETHER ALL THE REQUIRMENTS HAS COVERED OR NOR...
Compare the requirements to apply foe each use case steps....

With Requiremnts and Use cases and after comparing and finalising it , can start the coding.................

First implement main uce cases and second vertion do for the alternate paths...

Also checking on use cases we can identify correct requirements..............

Make sure ur requirements cover all the steps in the use cases for ur system..

Use use cases to find out about things ur customer forget to tell u......

Use cases will reveal any incomplete or missing requirements that might have to add to ur system....

page 139 hv definitions in a box...............



================================================================================

Analysys Unit 4-----------------------------------------------------------------------


Textual Analysis(nouns=classes/verbs=methods) is what to focus on, not just classes want to create.......
1. Identify the problem
2. Use cases can use to let you show , customers, managers and other developers how the system works in real world COntext....
3. Create use cases.Good use case must clearly and accuratly explains what a system does..
4. Consider use cases that have hv nouns(person,place,thing..)..
5. List all the nouns(dont't duplicate any).
6. probably allthe nouns may be classes in the system........................
7. But nouns which are not include to the system is not become classes..Like=:Owner,Outside
8. Recheck NOUN LISt extract from use case again.
9. With a good use case complete, textual analysis is a quick and easy way to figure out claases in the system..
  Actually textual analysis is tell you what to focus not just what the classes should create...
 some use case noune may not become to classes, but want to consider those at the desiging time....
 Action(verb of a use case) may be a class
no-------- some related things which are not nouns at the use case may be classes to the system, so want to think on that...

use case nounce will be classes
use case verbs will be methods of classes

*** Try to use objects for most og the cases
*** Try to make method delegation its make loosly coupling systems

A solid Line=: association(by reference,extension,inheritence)..
name of the attribute and multiplicity in the source class is written at the target end of the line.

Redrawing a class diagram is very easy than rewriting coding....so drawing class diagrams is better for analysing....
class diagrams great way to show overview of the system..
but dont show everything....

Probs of class diagrams..
Limited type information
don't tell how to code a method.
class diagram is only give a overview.

GOOD DESIGN-Unit 5-----------------------------------------------------------------------

If we hv same type number og objects(Guiter and Mandolean), we can think obout super class and sub class(instruments/mandolean and Guiter)
after want to abstract(inherit) that super class(we hv specefic notation arrow for inheritance)
Abstract classes are placeholders for actual implementation classes
we cla not inataintiate a abstract(super) class, only we can cdfine sub class of super class
Abstract classes defin behaviours....Sub classes implement those behaviours...

whenever U find  common behavoiurs in two or more places, Try to absract that behavoiurs in to a class , and then reuse that behaviour in the common class...
Abstract class can associate with another abstract class..
super class or sub class can associate with any enum types like classes

Aggregation (Square with line)+: one thing is made up of another thing..
Line with uncolored arrow head is generalisation..its for extending/inheriting..it is the generalisation..
Remove all the duplicate coding using abstract classes and encapsulation....

check U hv applied OO principles....
Check Ur design is loosly coupled...
Check Ur system can esily extend...

To check a software whethre it is well-designed , u try to change it, if it is very easy, then system is well-designed....

Interface is a good concept for make extendable softwares...
We can use interface for inherit common behaviours to number of sub classes from a super class just like inheriting a class..

Encapsulation helps for protect your classes from unnessesary changes...
*** In classes there are two types of methods...one is stable methods, otherone is vary methods...
Means...we hv to change some methods very reraly..But some methods hv to chnge very frequently....
So in this kind of situation,...We use encapsulation for un stable methods...Using INTERFASE...

EACH CLASS HAS ONLY ONE REASON TO CHANGE.....
Each class has only One reason to change.................

*****For each valuble task make diferenet classes...that is GOOOOOOODDDDDDDDDDDDDDD........

class with methods fro= start,stop ,carWash,Driver,Mechanics..is Not good..
make it 4 classes like automobile for start and stop, carWash,Driver,Mechanics...like this way...
Try to sperate coomon properties..this leads to encapsulation.....
================================================================================

Good Design.. 5(2)-----------------------------------------------------------------------

For changing part of a system , try to use java collection ........like Maps
then u  reduce number of sub classes......


take use of enum..........

----------------------------------------------------------------------------------
***

requirements are translated though analysis to a good design?
What are the best practices that can be applied in doing so?
how to write use case as a means to capture requirements,
object oriented analysis
and applying fundamental patterns to create good object oriented designs.
Generalized Responsibility Assignment Software Patterns (GRASP Patterns) that are primitive,
but powerful concepts that can be applied in creating good object oriented designs.




පළමු Struts2 Web application එක ලියමු - User ට Hello කියමු.

Struts2 Framework එක භාවිතයෙන් සරල application එකක් ලියන හැටි කියන්නයි මේ ලිපිය ලියන්නේ.

 Web application එකක් පිළිබඳව මූලික දැනීමක් ඇතැයි අපේක්ෂා කරනවා. මන්ද හැමදෙයම මුලසිට සරලව විස්තර කිරීම අපහසු නිසා. මේ ලිපියේ කරුණු ගැන ගැටළුවක් ඇත්නම් විමසන්න comment තීරුව භාවිතා කරන්න. එලෙසම යම් වරදක් ඇතොත් පෙන්වා දෙන්න අමතක කරන්නත් එපා.

මේ සඳහා ලිවිය යුතු files මේවාය.
 1) Logon.jsp
 2) Struts.xml
 3)  LoginAction.java
 4)  ApplicationResource.properties
 5) Welcome.jsp
 6)  Web.xml


එක් එක් file වල කාර්යභාරය කෙටියෙන්...

 1) Logon.jsp
    -User ගෙන් අවශ්‍ය input ලබාගැනීම සඳහා
  
 2) Struts.xml
    -  Struts හි Configurations  සඳහා..
        request එකට අදාළ action class එක සහ method එක සොයාගැනීම
        response එකට අනුව display කළයුතු page එක සොයාගැනීම

 3)  LoginAction.java
    -Business logic එක ඇත්තේ මෙහිය.
     ලබාගත් input, variable වලට assign වන්නේ මෙහිදීය. 

 4)  ApplicationResource.properties
     වෙනම properties file එකක් යොදා ගැනීමෙන් labels සහ error messages ලබාදීම පහසු කරගත හැක.

 5) Welcome.jsp
     - Final Output එක display කරන page එක


 6)  Web.xml
    - Web application එකේ configurations  ලබාදීම සඳහා
     

ඊළඟට code සහිතව සහ වඩා විස්තරාත්මකව සළකා බලමු.



 1) Logon.jsp

මෙය Login JSP Page එකයි.

01. <%@ page contentType="text/html; charset=UTF-8"%>
02. <%@ taglib prefix="s" uri="/struts-tags"%>
03. <html>
04. <head>
05. <title>Struts 2 - Login Application | PMTDB </title>
06. </head>
07.
08. <body>
09. <h2>Struts 2 - Login Application</h2>
10. <s:actionerror />
11. <s:form action="login.action" method="post">
12.    <s:textfield name="username" key="label.username" size="20" />
13.    <s:password name="password" key="label.password" size="20" />
14.    <s:submit method="execute" key="label.login" align="center" />
15. </s:form>
16. </body>
17. </html>



Web Application එක Run වෙනවිට මුලින්ම දර්ශනය වන්නේ මේ පිටුවයි.
මෙහිදී User ගෙන් username සහ password ලබාගැනෙයි. Login Button එක Click කළ විට Login request එකක් generate වෙයි. මේ request එක action class එකකට ගොස් අදාළ conditions පරීක්ෂා කළ යුතුය.

ඉතින් මේ request එක යා යුතු action class එක කුමක්දැයි සොයාගන්නේ කෙසේද? එය සොයාදෙන්නේ Struts.xml file එකයි.

2) Struts.xml


 01. <?xml version="1.0" encoding="UTF-8" ?>
02.   <!DOCTYPE struts PUBLIC
03.    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
04.   "http://struts.apache.org/dtds/struts-2.0.dtd">

05. <struts>
06.    <constant name="struts.enable.DynamicMethodInvocation"
07.        value="false" />
08.    <constant name="struts.devMode" value="false" />
09.    <constant name="struts.custom.i18n.resources"
10.        value="ApplicationResources" />

11.     <package name="default" extends="struts-default" namespace="/">
12.        <action name="login" method="execute"
13.            class="PMTDB.struts2.LoginAction">
14.            <result name="success">Welcome.jsp</result>
15.            <result name="error">Login.jsp</result>
16.        </action>
17.        </package>
18. </struts>






action name එක Login නම් යා යුතු Action class එක LoginAction බවද ක්‍රියාත්මක විය යුතු method එක    execute බවද ඉහත file එකේ සඳහන් වෙයි.

එපමණක් නොව method එක execute වීමේදී ලැබෙන result එක අනුව ඊළඟට යා යුතු pages සඳහන් වෙන්නේ ද මෙහිමය. result එක success නම් Welcome.jsp page එකට යා යුතු බවද result එක error නම් නැවත Login.jsp page එකට යා යුතු බවද ඉහත සඳහන් වී ඇත.

 3)  LoginAction.java

           package PMTDB.struts2;

                import com.opensymphony.xwork2.ActionSupport;

               public class LoginAction extends ActionSupport {
                       private String username;
                       private String password;

                  public String execute() {

                       if (this.username.equals("PQR")
                          && this.password.equals("PQR123")) {
                          return "success";
                     } else {
                         addActionError(getText("error.login"));
                       return "error";
                      }
                       }

                  public String getUsername() {
                    return username;
                   }

                   public void setUsername(String username) {
                  this.username = username;
                  }

                  public String getPassword() {
                  return password;
                    }

                 public void setPassword(String password) {
                 this.password = password;
                    }
                  }





Action class එකේදී username සහ password යන properties, declare කර ඇත. එලෙසම ඒවාට getters සහ setters ලියා ඇත.

 Action class එක ActionSupport නම් class එක inherit කර ඇත.

 public class LoginAction extends ActionSupport {

 execute method එක තුළ username සහ password, check කර ඇත. username යන්න PQR නම් සහ password යන්න PQR123 නම් success යන්නද නැත්නම් error යන්නද return කර ඇත.

 4)  ApplicationResource.properties

ApplicationResources වෙනම properties file එකක් යොදා ගැනීමෙන් labels සහ error messages ලබාදීම පහසු කරගත හැක.


label.username= Username
label.password= Password
label.login= Login
error.login= Invalid Username/Password. Please try again.



5) Welcome.jsp

Action class එකේදී success return වුනොත් පෙන්නුම් කරන්නේ පහත jsp එකයි.

01. <%@ page contentType="text/html; charset=UTF-8"%>
02. <%@ taglib prefix="s" uri="/struts-tags"%>
03. <html>
04. <head>
05. <title>Welcome</title>
06. </head>
07.
08. <body>
09.     <h2>Hello, <s:property value="username" />.......!</h2>
10. </body>
11. </html>



මෙහිදී කලින් ලබාගත් username එක යොදාගෙන user ට Hello කියා ඇත.

6)  Web.xml

පහත ලබාදී ඇත්තේ configurations සඳහා වන Web.xml එකයි.

01. <?xml version="1.0" encoding="UTF-8"?>
02. <web-app id="WebApp_9" version="2.4"
03.    xmlns="http://java.sun.com/xml/ns/j2ee"
04.    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
05.    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
06.
07.    <display-name>Struts2 Application | PMTDB </display-name>
08.    <filter>
09.        <filter-name>struts2</filter-name>
10.        <filter-class>
11.            org.apache.struts2.dispatcher.FilterDispatcher
12.        </filter-class>
13.    </filter>
14.    <filter-mapping>
15.        <filter-name>struts2</filter-name>
16.        <url-pattern>/*</url-pattern>
17.    </filter-mapping>
18.    <welcome-file-list>
19.        <welcome-file>Login.jsp</welcome-file>
20.    </welcome-file-list>
21.
22. </web-app>

MVC Architecture

මේ design pattern එකෙන් කරන්නේ web application එකක ඇති components කොටස් තුනකට වෙන් කිරීමයි.
Model, View සහ Controller යනුවෙන්.

මේ component එක එකට පැවරුනු වගකීම් තියෙනවා.මේවා එකිනෙකින් ස්වායත්තයි. එක component එකක වෙනස් කිරීමකින් අනිත් component එකට බලපෑමක් නැත.(ඇත්නම් ඒ ඉතා සුළු වශයෙනි.)

මේ එක එක component වලට පැවරෙන වගකීම් මොනවාද?

Model

මෙය වගකියනු ලබන්නේ database එකෙන් data ලබාදීමට සහ database එකට data, save කිරීමටයි. සියළු business logic implement කරන්නේ මෙය තුලයි.

.User විසින් View එක හරහා ඇහුල් කරන data,db එකට save කිරීමට පෙර Model කොටසේදී check කිරීම කරනු ලබයි.Model එකට අයිති කොටස් වන්නේ

Data access,
Data Validation සහ
Data saving logic

යන ඒවායි.

View

application එකේ user ට පෙනෙන කොටස නිරූපනය කරන්නේ view මඟිනි.

-user ගෙන් input ලබාගැනීම
-controller එක වෙත requests, send කිරීම
-controller එක මඟින් responses ලබාගැනීම
-user ට output එක display කිරීම

මෙහි කාර්ය භාරය වෙයි.

View Component එකට අයිති වෙන්නේ..

-HTML
-JSP
-Custom tag libraries සහ
-Resourse files ආදියයි.

Controller

Model සහ View අතර අතරමැදියා ලෙස කටයුතු කරන්නේ Controller එකයි.

Client ගෙන් request එක view එක හරහා ලැබුනු විට, model එකේ අදාල business logic එක execute කරවා, ලැබෙන output එක view හරහා user ට ලබාදීමේ වගකීම පැවරෙන්නේ controller එකටයි.


Controller component එකට අයිති වන්නේ
-Action
-Action Servlet
-Action Form සහ
-Struts-config.xml

ආදියයි.

10. Named Queries, Lazy loading සහ Cascade ගැන..


Named Queries

මෙම queries, define කර ඇත්තේ mapping xml file  එකේදීය. අවශ්‍ය විට මෙම නමින් call කළ හැකිය.Application code එක තුළ sql ලිවීම වළකී.

උදා:


<sql-query name = "empdetails">
   <return alias="emp" class="com.test.Employee"/>
      SELECT emp.EMP_ID AS {emp.empid},
                 emp.EMP_ADDRESS AS {emp.address},
                 emp.EMP_NAME AS {emp.name}
      FROM Employee EMP WHERE emp.NAME LIKE :name
</sql-query>

මෙම Named query එක call කරන්නේ කෙසේද ?



List people = session.getNamedQuery("empdetails")
    .setString("TomBrady", name)
    .setMaxResults(50)
    .list();

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

Lazy loading

lazy=true මඟින් performance improve වෙයි.Collection එකක් associate වී ඇත්නම්, එහි elements load වන්නේ, ඒ සඳහා වෙනම call කළොත් පමණි.

Parent object එක load කරන විට child objects load කළයුතුද නැත්ද යන්න set කරන්නේ මෙමඟිනි.

Parent class එකේ mapping සිදුකරන විට මෙය ලබාදිය යුතුය.

lazy=true මඟින් අදහස් වන්නේ child objects load නොකළ යුතු බවයි.(default)

එය  load කිරීමට නම් වෙනම parent.getChild() call කළ යුතුය.

සමහර අවස්ථාවල parent object එක සමඟම child object එකත් load කිරීම අවශ්‍යය වෙයි.
 එවිට lazy=false දිය යුතුය.


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

Cascade


1) cascade="none", (default) -:association., ignore කරන ලෙස දැන්වීමට

2) cascade="save-update" -: object එක save/update කරන විට, transaction commit කරන විට association , navigate කර persistent instances වලටත් අදාළ වෙනස්කම් කරන්න.


3) cascade="delete" -: object එක delete කරන විට association , navigate කර persistent instances, delete කරන්න.

9. Hibernate සහ Spring, integrate කරමු.



මෙහි ප්‍රධාන පියවර දෙකකි.
1. HibernateTemplate එක Spring හි declare කිරීම
2. එයට SessionFactory  එක සම්බන්ධ කිරීම


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



Spring වල ඇති HibernateTemplate, Hibernate session සඳහා වඩා abstract layer එකක් ලබාදෙයි.

HibernateTemplate හි ප්‍රධානම කාර්යය වන්නේ Hibernate sessions open කිරීම සහ close කිරීමේ වැඩ සරල කිරීම සහ Hibernate-specific exceptions, Spring ORM exceptions බවට පත් කිරීමයි.

[Hibernate 2 ට අදාළව නම් මෙය Checked Hibernate exception එක, Unchecked Hibernate Exception එකක් බවට පත් කිරීමයි.

HibernateTemplate එක Spring හි configure කරන ආකාරය පහත xml එකේ දැක්වෙයි.


<bean id="hibernateTemplate"

class="org.springframework.orm.hibernate3.HibernateTemplate">
 <property name="sessionFactory" ref="sessionFactory" />
</bean>




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


Hibernate Session Object එකක් සඳහා reference එකක් ලබාගැනීමේ සම්මත ක්‍රමය වන්නේ Hibernate හි Session Factory Interface එකේ implementation එකක් හරහාය.

Hibernate sessions, open කිරීම, close කිරීම සහ manage කිරීම Session Factory හි වගකීමයි.

පළමු කාර්යය වන්නේ Hibernate Session Factory Bean එක Spring වල configure කිරීමයි. 


Classes, tables map කරන්නේ annotations මඟින් නම් මෙම Hibernate Session Factory instance එක ලබා දෙන්නේ AnnotationSessionFactory Bean එක මඟිනි.

Mappings සිදු කරන්නේ xml මඟින් නම් මෙය සිදු කරන්නේ LocalSessionFactoryBean මඟිනි.


<bean id="sessionFactory"

class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
 <property name="dataSource" ref="dataSource" />
 <property name="annotatedClasses">
  <list>
   <value>hibernate.Employee</value>
  </list>
 </property>
 <property name="hibernateProperties">
  <props>
   <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
   <prop key="show_sql">true</prop>
  </props>
 </property>
</bean>

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



දැන් HibernateTemplate එක Declare කරලා අවසන්.
එලෙසම එය SessionFactory එකට සම්බන්ධ කර තියෙන්නේ.

දැන් අප සූදානම් Database එකට data persist කරන්නට සහ එයින් data retrieve කරන්නට.

8. SessionFacory,session සහ HibernateTemplate හි භාවිතය


SessionFacory



Application එක සඳහා session instances ලබා දෙන්නේ SessionFactory එක මඟිනි.

සාමාන්‍යයෙන් Application එකක් සඳහා පවතින්නේ එක SessionFactory එකකි.

Application එක Hibernate මඟින් databases කීපයක් access කරනවා නම්, එක් එක් database එක සඳහා වෙන වෙනම SessionFactory අවශ්‍යය වෙයි.

Many-To-Many Relation Mapping උදාහරණයේදී Session එක භාවිතයෙන් objects, save කරන ආකාරය සළකා බලමු.

packagge abc.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class SavingTest{

public static void main (String args[] ) {

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

Meeting m1 = new Meeting ("HR Meeting") ;
Meeting m2 = new Meeting ("Finance Meeting");

Employee e1 = new Employee ("kamal","perera",20000);
Employee e2 = new Employee("nimal","silva",30000);

e1.getMeetings.add(m1) ;
e1.getMeetings.add(m2);
e2.getMeetings.add(m1);

session.save(e1);
session.save(e2);

session.getTransaction();
commit();
session.close();

}
}


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

HibernateTemplate


HibernateTemplate යනු helper class එකකි.
එය hibernate data access code එක සරල කරයි.

එයින් session open කිරීම සහ close කිරීමද code එක execute වූ පසු transaction, commit හෝ rollback කිරීමද සිදුකරන නිසා ඒ සඳහා code ලිවිය යුතු නොවේ.

නමුත් Hibernate 4 version එකෙන් මෙය ඉවත් කර ඇත.

7. Many-To-Many Relation Mapping


පහත දැක්වෙන්නේ Many-To-Many relationship එකක් map කරන ආකාරය.


Meeting සහ Employee classes දෙක අතර සම්බන්ධය Many-To-Many ලෙස ගනිමු.

එනම් එක Meeting එකක Employees ලා බොහෝ සිටිය හැක.
එක Employee කෙනෙක් බොහෝ Meeting ගණනකට සහභාගි විය හැක.


a)  package abc.hibernate;

import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.ManyToMany;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.CascadeType;





@Entity
@Table(name="employee")
public class Employee{

@Id
@GeneratedValue
@Column(name="emp_id")
private Long empId;

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

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

@Column(name="birth_date")
private Date birth_date;

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

@ManyToMany(cascade={CascadeType.ALL })
@JoinTable(name="employee_meeting",
                       joinColumns={@JoinColumn(name="emp_id")},
                       inverseJoinColumns={@JoinColumn(name="meeting_id")})
private Set<Meeting> meetings = new HashSet<Meeting>(); 

public Employee(){
}

public Employee(String firstname, String lastname, Date birthdate, double salary){
this.firstName = firstname;
this.lastName = lastname ;
this.birthDate = birthdate ;
this.salary = salary ;
}

//Getter and Setter methods

}




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




b)   package abc.hibernate;


import java.util.Date;
import java.util.HashSet;
import java.util.Set;



import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.ManyToMany;


@Entity
@Table(name="meeting")
public class Meeting {


@Id
@Column(name="meeting_id")
@GeneratedValue
private Long meetingId ;


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


@Column(name="meeting_date")
private Date meetingDate;


@ManyToMany(mappedBy="meetings")
private Set<Employee> employees = new HashSet<Employee>();


private Meeting(String subject){
this.subject= subject;
this.meeting_date = new Date();
}


//Getters and Setters


}

6.One-To-Many relation mapping


පහත දැක්වෙන්නේ One-To-Many relationship එකක් map කරන ආකාරය.


Department සහ Employee classes දෙක අතර සම්බන්ධය One-To-Many ලෙස ගනිමු.

එනම් එක Department එකක Employees ලා බොහෝ සිටිය හැක.
නමුත් එක Employee කෙනෙක් අයත් වන්නේ එක Department එකකට පමණි.

a)  package abc.hibernate;

import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.ManyToOne;
import javax.persistence.JoinColumn;

@Entity
@Table(name="employee")
public class Employee{

@Id
@GeneratedValue
@Column(name="emp_id")
private Long empId;

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

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

@Column(name="birth_date")
private Date birth_date;

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

@ManyToOne
@JoinColumn(name="deptment_id")
private Department Department;


public Employee(){
}

public Employee(String firstname, String lastname, Date birthdate, double salary){
this.firstName = firstname;
this.lastName = lastname ;
this.birthDate = birthdate ;
this.salary = salary ;
}

//Getter and Setter methods

}






@JoinColumn යනු Entity දෙකක් සම්බන්ධ කිරීමේදී map වෙන column එකයි.
----------------------------------------------------------------------------




b)   package abc.hibernate;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.OneToMany;


@Entity
@Table(name="department")
public class Department{


@Id
@GeneratedValue
@Column(name="department_id")
private Long departmentId;




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




@OneToMany(mappedBy="department")
private Set<Employee> employee ;


//getters and setters


}

5. One-To-One relation mapping


Hibernate mappings වලදී table අතර relations, map කිරීම ඉතාම වැදගත් කාර්යයක්.

පහත දැක්වෙන්නේ One-To-One relationship එකක් map කරන ආකාරය


Employee සහ EmployeeDetail නම් class දෙක අතර සම්බන්ධය One-To-One ලෙස ගනිමු.

එනම් එක Employee කෙනෙකුට ඇත්තේ එක EmployeeDetail එකකි.
එලෙසම එක EmployeeDetail  එකක් සම්බන්ධ වන්නේ එක Employee කෙනෙක් සමඟ පමණි.


a) package abc.hibernate;

import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="employee")
public class Employee{

@Id
@GeneratedValue
@Column(name="emp_id")
private Long empId;

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

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

@Column(name="birth_date")
private Date birth_date;

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

@OneToOne ( mappedBy="employee" cascade=CascadeType.ALL)
private EmployeeDetail employeeDetail;


public Employee(){
}

public Employee(String firstname, String lastname, Date birthdate, double salary){
this.firstName = firstname;
this.lastName = lastname ;
this.birthDate = birthdate ;
this.salary = salary ;
}

//Getter and Setter methods

}




b)  package abc.hibernate; 

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;


@Entity
@Table(name="employeedetail")
public class EmployeeDetail{


@Id
@Column (name="employee_id", unique=true, nullable=false)
@GeneratedValue(generator ="gen")
@GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property",
                                                                                     value="employee"))
private Long employeeId;


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

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


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

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


@OneToOne
@PrimaryKeyJoinColumn
private Employee emploee ;

public EmployeeDetail(){
}


public EmployeeDetail (String street, String city, String state, String country ) {
this.street= street ;
this.city = city ;
this.state = state ;
this.country = country ;
}

//getters and setters

}

4. Hibernate mappings, Annotations භාවිතයෙන්...



පහත දැක්වෙන Employee class එක simple POJO class එකක්.

මෙහිදී hibernate mapping සිදු කර තිබෙන්නේ annotations භාවිතයෙන්.



package abc.hibernate;

import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="employee")
public class Employee{

@Id
@GeneratedValue
private Long empId;

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

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

@Column(name="birth_date")
private Date birth_date;

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

public Employee(){
}

public Employee(String firstname, String lastname, Date birthdate, double salary){
this.firstName = firstname;
this.lastName = lastname ;
this.birthDate = birthdate ;
this.salary = salary ;
}

//Getter and Setter methods

}

ඉහත  annotations වල භාවිතය පහත පරිදිය.

@Entity -  මෙමඟින් class එක entity එකක් බව ( persistent POJO class එකක් බව ) ප්‍රකාශ වෙයි.

@Table(name="xxx") -  class එක  map වියයුතු table එකේ නම


@Id -  මෙමඟින් මේ entity එකේ identifier property එක ප්‍රකාශ කරයි.

@GeneratedValue - primary key එක auto generate විය යුතු බව

@Column(name="xxx") -  attribute එක  map වියයුතු column එකේ නම

3. Hibernate, configuration කරන්නේ කොහොමද?

http://javasamagawase.blogspot.com/2012/07/hibernate-configuration.html
මේ සඳහා වෙනම configuration file එකක් ලිවීමට පුළුවන්.
(hibernate.cfg.xml)
xml file එකක් වෙනුවට properties file එකකිනුත් hibernate configurations ලබාදිය හැක.
නැත්නම් මේ configuration details , spring-config.xml වැනි configuration file එකකට ඇතුළත් කරන්නත් පුළුවන්.
(Hibernate සහ spring ,integrate කරන project එකකදී)
 hibernate.cfg.xml file එකක් පහත දැක්වෙයි.

<?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”>

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->
               

<property name=“connection.driver_class”>com.mysql.jdbc.Driver
</property>

<property name=“connection.url”>jdbc:mysql://localhost/firsthibernate
</property>

<property name=“connection.username”>root</property>
  
               <property name=“connection.password”>root</property> 

    
<!--sql dialect-->

<property name=“dialect”>org.hibernate.dialect.MySQLDialect</property>

<!-- Echo all executed SQL to stdout -->
                   
                  <property name=“show_sql”>true</property>
                <property name="hibernate.connection.pool_size">10</property>  

                   <!-- mapping සිදු කරන්නේ annotations මඟින් නම් -->     
       
<mapping class="employee.Employee" />

<!-- mapping සිදු කරන්නේ xml මඟින් නම් -->

<mapping resource="employee.Employee.hbm.xml" />



</session-factory>

</hibernate-configuration>

දැන් මේ configuration details විස්තර සහිතව සළකා බලමු.



 පළමු properties හතරෙන් දැක්වෙන්නේ MySQL database connection එක සඳහා අවශ්‍යය 

configurationsවෙයි.


driver_class යනු කුමක්ද? DBMS එකට අදාළ JDBC driver class එකයි. 
උදා: com.mysql.jdbc.Driver, org.postgresql.Driver,  
oracle.jdbc.driver.OracleDriver

url එක මඟින් database path එක දිය යුතුය.username, password යනු database එකට connect වීම
සඳහා දිය යුතු username password වෙයි.

dialect යනු hibernate මඟින් generate කළයුතු specific sql variant එකයි. Database එකට අදාළ sql ,
generateකිරීම සඳහා මෙය ලබාදිය යුතුය. උදා: org.hibernate.dialect.MySQLDialect, 
org.hibernate.dialect.PostgreSQLDialect, org.hibernate.dialect.OracleDialect ,
org.hibernate.dialect.SQLServerDialect

show_sql යන්න true කර ඇත්නම් console window එකට සියළු sql command ලබාදෙයි.


pool_size යනු hibernate database connection pool එකේ ඇති උපරිම waiting connections 
ගණනයි.

අවසන mapping files ඇති තැන ලබා දී ඇත.