• No results found

Hi Bernet

N/A
N/A
Protected

Academic year: 2021

Share "Hi Bernet"

Copied!
176
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

C po ga ficem&$.z~,xa . ,

.

. ., : ,, . . : . . mo b 40,g ~( g~ ~e g ~$ J) us y? ue ~. 3 pus (q ~~ es ~g ); ~r mn )lb ip n . . ; su og el n~ e~ 8u oa . . . . . k . . . . .. . . . . . h LL

*p

m n

of

ii

&.

a~

~@

ja

q.

: . ...:. , ... c I ..: . . #:; , i :i,i.,. c , ,.~L l/ ~m

nofi

u :a

y m amp b

aw03 s

fi

vm

~a

;~

pm

.a

~a

y~

ua

-

*...

a nofi

au

of

iu

~

? ,' ! > > & . .< i ,, - , . ~ 0 4 ~ ~ ~

3 . . <:?

':w3nofi

nofi aucpfiun

.

fiu!qjfij~na

mvaT99

(3)

' Iibel-nate is built on top of Jdbc.

, .

;I bernate not only takes care of the mappings from java classes to

..:::base tables but also providesdata query and retrival facilities and

::xi significantly reduce development time otherwise spent with

:nanualdata handling SQL and JDBC.

i irbemate's goal is to relievethe developer Gom 95% of common data

;msistencerelated programming tasks.

:! j ' ; .,

:i;;ernate is used to.Persistance .theobject state in the persistence

!.r~edia like database.

iii order to store state of an object in the:;relational database ORM is

!jetter- ., . than . plain Jdbc.

:libemate is a solution for ORM (Object Relational Mapping System).

.!t refirs to the technique of mappinga data fiom . an . object model with

S Q ~ based commands.

~ r a m e Gorks which are using ORM technique likeTopLinks, IBatis,

:-libemateand Ejb EntityBean, in order to store the state of ?bject.

.--, .

.kjb EntityBian can not be used in non-ejb applications. Themain . .

.. j.,

limitation of thisis performance. ..::::. . . . _ . . . . .. ‘..-- . ..,. , . . ..

.f

.. y e ..-:.:.:. use JDBC: then we;want to.hard-.~.qde the sql queries insid&he

' . . L-i --.. ..> ,:I . . . . b . .: . . ,

,f@z:file. If we use ~ i b & ~ & ~ , i & & we &fi7t require to hardcod; the ;

.! ., <: ... . ,

?QL, ;q

;

.; ,.

ueries in our Java program. : : . : : . ; :

SQL 4ukrjes will automatically gene&tid>by:~ibt$-nate depending on

. .

;:r database. S o whdnever we are going to changethe;.database ... . then

l l v g file is.&ot required to modify. ~ u s t changing theG~,~.?ddriver

.::;z~ss in the configuration file is enough. Then hibernate will generate

1.

. . . i . ::.ri~.!eries ,.; .,. . automatically based on database.

!.:; <;;. .;;: ::

: : YZ1:..r. x-u,uw- y e . using.straightaway . . Jdbc in java:program then achieving

'r~,&sa@i'bn . ., . . . ~ a n a ~ e m e n t .. .. and Cache Management are very.di!fficult. . ,‘.:!

'.nd al$d'ri&d = .*,, to -te s o r e -$..$ . code

. .. . and interac$Gn;ae:yev:Id;&~vlt. . .. x, +\: ..&.: ;.$c..5%~. ,,, ,... = ::

l

; :,,ibernat&i&'haVing

s o ~ s

.&e&hds. to interact wif&@at:&2se (Those

. . ; ii.::-..

-l:relhods cai in&&ct with d&abL$e .. . t h o u g h Jdbc only) and also very

-::,A. :nethod call's wehave to keepin ydur java progrzm.

. j ~ . ~ + > a file will be independent of sql queries or database.

.? \."l S1

(4)

Here Java file sending a action to hibernate but not sql queries. Based on the;action (i.e insert or update or select) hibernate will generate sql query and sends to the database.

If you hiive&equirement of using some'datavery frequently, instead of readingifiom database every time, read once and keep in the cache and

then 2-?? time onwards read from the cache, it reduces number of

network. calls. . .

. . . ,.,

. . ,.. .

If you are using Hibernate, you can change the databgeone to another

at the time

6%

_ > . . .development . itself.

. . . . . .. .

For exampleatthe time of development you used mysql aft;;.

production your client/customer wants to change database to Oracle '

thgn;ho need to do%chang&i in yourjava code. You need to do changes

in:th+&nfiguration . . ;. .....-. file and:can execute . . . :very . . , successfully. . . . . ." . . .

Hibe&$ti$id typically used in ~ a v ~ . ~ w i ~ ~ ~ . a ~ ~ ~ a t i o n s , . . Java Servlet ' .;

applicat?ori$,:or J2ee applications using session-beans.

Hibernate supports "Transactions" (~ransaction.;means making

multiple units,& a single bundle i.e a transaction can contains insert,

update, delete,iif .: ... any one query fails to execute then remaining also

. . . . . . willcnot ._ .. . , . . . . - . - . _ . . . . . ,

execute$

:.. .. .. L . . :>.> - -. :.,; .: ~ ::; , - , ; ... . We >d.$k:.achie~s~ ? .." . ' ,~. .*.. .

! - .mapping through Hibe&ie!,very easely. $<::

" ,... , :.. _. . ., ...;,.. : . +>:. ?< , .. :

,,; .-.:. :< :.,: .: :::-. . .. ...

m By H i E e m a t e ~ & >,. ... ... .

can achieve where conditi(jn$ !very

simp]e f:.(i :$

. .

By Hibernate-managing joins is very easy.

Hibernate is developed in java so, it is platform independent.by this we can achieve pure object oriented (database ioteractions also).

Hibernate can be used for any kind of java application that can be standalone, web-application, or enterprise application in where.the database interaction is required.

Hibernate uses Object oriented querying language.

Hibernate is free t c use no need to buy any licences. It is also a

opensource, we can download the source code and can enhance. Usage of Hibernate is nothing but using sessipn object effectively. Hibernate maintains two level cache.

(5)

A major portion of the develoument of an enterprise application involves the creation and maintenance of the persistence layer used to store and retrieve objects from the datzibese of choice.

If changes are made to the underIying database schema, it can be

expensive to propagate those changes to the rest of the application. Hibernate steps into fill this gap, providing an easy to use and powerfull object relational persistence fi-amework for java applications.

Hibernate provides support for collections and object relations, as well a s composite types. Userdefined data types and composite primary keys give additional flexibility to support legacy applications.

Hibernate key features: --

Natural programming model: Hibernate supports natural 00 idiom,

inheritance, polymorphism, composition and the java collection framework.

Support for ultra-fine-grained object models: a rich variety of

mappings for collections and dependent objects.

No build-time bytecode enhancement: there is no extra code

genaration or bytecode processing steps in your build procedure.

Extra scalability: Hibernate is extremely perfomant has dual-layer

cache architecture, and may be used in a cluster.

The query 'language: Hibernate addresses both sides of the problem;

not only how to get objects into the datzbase, but also how to get them

<ut again. ' '

Support for application transactions: Hibernate supports both long-

lived persistance contexts and detachlresearcn and takes care of optimistic locking automatically.

Freelopensource: Hibernate is lisensed under the LGPL (Lesser

GNU Public Lisesce). , -

:

Ejb3.0: Hibernate implements the persistance API and quarey

lailguage defined by EJB3.0 persistence, two members of the

1-J;ibernate team are active in i'ne expert group. Ii provides t h e e hfi-

featured query facilities those are 'Hibernate Query Language'. 'Hibernate Criteria Queiy7, 'dialect of the database'.

Hibernate is scalable: Hibernate is very perfoment and due to its

dual-layer architecture can be used in the clustered envir~nment.

(6)

Less rlcve!opment time: Hibernate reduces the development timings

a s i t supports inheritance, polymorphism, composition and the java

collection framework.

Automatic key genera tion: Hibernate supports the automatic

generation of primary key.

Enhanced Criteria query MI: with full support for

projectionfaggregation and subselects.

-

EJB3-Stylepersistance operation: defines the create () and merge ()

operations-which are slightly different to Hibernate's saveorupdate ()

and saveorupdatecopy () operations. Hi bernate3 will support all four

operations as methods of the session interface.

Hibernate X M L binding enables data to be represented as XML and

POJOs interchangeabily,

The EJB3 draft specification support for POJO pers-istance and annotations.

---.

lmoernare Based kppiication Architecture:

Configuration

ExIl

Persistant Objects 1 Transaction

1

. - . . . .-. . . . .

(7)

To use Hibernate, it is required to create a java class that represents the table

in the database and then map the instance variable in the class with the

c o l ~ m n s in the daiabase. Then Hibernate can be used to perform operations

on the database like select, insert, update and-delete the records in the table. Hibernate architecture has three main components:

1 . connection Management:

2. transaction Management:

3. object Relational Management:

Hibemate provides a,lot of flexibility in use. It is called 'lite' architecture

when we only use the object relational mapping component. w i l e in 'full cream7 architecture all the three component Objects Relaational Mappings are used.

Hibematre is being used with other configuration management aqd

- transaction management tools. For example apache DBCP is u s e d , f ~ r

< -

conneptioq puuiiiig ~iLLii tile Hibernate.

.. 9

Pre requisits-to use hibernate:

1. Any one of the database.

2. For that database 4" type of driver jar file.

3.- Java ~ e v e l o ~ m e n t Kit of J2SE.

4. 1f you are using:web-application then only any one of the webserver.

I, .

The officik-website for hibernate is 'www.hibernate.org7.

In order to interact with database by using Hibernate need to update classpath or buildpath with relavent jar files.

lnorder to use hibernate framework we should ~ p d a t e classpath or buildpath with the relavent and dependent JAR files those are: -

1. hibernate-3.2.jar file 2. Driver JAR file

(8)

Hibernate API Session (orp.hibernate.Session):

Session object is similar to the HttpSession 0bject.s A single-threaded, short-lived object representing a conversation between the application and

the persistent store. Wraps a JDBC connection. Factory for T r a n s a c t i o n .

Holds a mandatory (first-1evel)cache of persistent objects, used when navigating the object graph or looking up objects by identifier.

SessionFactory (or~.hiberna te.SessionFactorv):

SessionFactory is a singletone object for entire application there will be one

sessinfactory object. A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC

connection. Factory for T r a n s a c t i o n . Holds a mandatory (first-level)

cache of persistent objects, used when navigating the object graph or looking up objects by identifier.

Configuration (or~.hibernate.cf~.Confipuration):

.. ., . .

. . .

In order to complete . .. . , configurationi::df&&of fi%hibernate we use this class.

. . . . . . .; ... ' . . . . . . .: >. . Query(org.hibednate.cf~.quew):

In order to c o n s t f u c t ' ~ ~ ~ queries we use this interface. Not .only this

interface we can a1s.o use Criteria interface.

Transaction (org.hibernate.Transaction):

(Optional) A single-threaded, short-lived object used by the apclication to speciijr atomic units of work. Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases. However, transaction

demarcation, either using the underlying API or Transaction, is never optional!

With hibernate API jdbc get the hql queries and it interact with the Jdbc and it will convert the hql queries in to the0sql queries to interact with the

database.

(9)

Getting Start with Hibernate:

Hibernate is free to use and it is opensource

.

There is a website to do\mload (lvww.hibernate.01-c). At the time of downloading we will get one zip file i.e hiberna te-3.2.3.ga.zip.

Unzip it to the favourable location. Inside unzipped folder you can

find many folders. Among them hibernate3.jar (i.e core hibernate)

and jar files in the lib (hibernate dependence .jar files) are required to

develop any hibernate related application.

Take both jar files and update classpath or buildpath (in eclipse) or

copy into lib folder of web application. Development steps f o r Application proiect:

For Every framework there will be one configuration file Eg: for struts

struts-config.xm1. Like wise for hibernate also there is one config file i.e hi berna te.config.xm1

First develop one hibelxa:~.config.~'~:i fcr ynvr r~pp!iclticn wder

classpath. Inside this xml file we have to explian about.

I. DriverClassName.

2.

'Lm.

3 . Usemame to connect to database;

,4. Password to connect to database.

5. Type of 2nd level cache.

6. Dialect class. Through this we are updating database

type (Dialect means pronouncing same language in different accents).

, ... . . . . . :,

Develop "POJO . .. class"(Pl~iq@ld~Java . . I :.. . .!.. ': Object). It is similar to

usebean or forrri bean.

:;;

A .! . ". . :

For every pojo cl&&develop one hbm (hibernate mapping) file.

Update ~ o n f i ~ u r a t i o n ' f i l e with hbm file path.

Write client program .Inside this, we have to f ~ l l o w following steps.

I . Open hibernate. session.

2. Start transacfio~n:

3. Use transaction ::... .: .: ' . '

4. Commit transaction 5. Close the session

(10)

Developing core iava related proiect:

Developing a simple helloworld stand alone application by using mj-Sql database.

I . Go to scljpse and create one core java related project.

2. Now update the buildpath with hibernate3.jar (i.e core hibernate)

,

jar files from lib(hibemate dependence .jar files) and the Driver jar

file.

3. Now develop hiberna te.cfg.xml file inside src folder

<?xml version=' 1 -0' encoding='utf-8'?>

<!DOCTYPE hibemate-configuration PUBLIC

11-

.

//u;L~-,.+-

.

A ..wbi ,laLc,lTibelmate Configuration DTD 3.0//ENn

" http://hi bemate.sourcefor~e.net/hibernate-configuration-3

-

.O.dtd1'>

<!-- Database connection settings -->

<property name="connection.driver classw>

c0m.m ysql . j d b c . ~ ~ i v e r < / ~ r o ~ e r t ~ > <property name="connectj o;l.urll'>

jdbc:mysql ://local host/larac/property>

<property narne="connection.usernarne">root</property>

<property name="connection.password''></property>

<I-- SDBC co~lnectlon poo! fuse the built-in) -->

<property r?ame="connecti on.pool - sizeu> l </property>

<!-- SQL dialect -->

<property narne="dialectfl>

org.hibemate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's auiornatic session context management -->

<-propefi;.; name="curi-ent - sessio~l - context

-

class">thread</property>

(11)

<!-- Disable the second-level cache -->

<property name="cache.provider - classw>

org-hi bemate.cache.NoCacheProvider</prope~> .

-

. -

<!-- Echo all executed SQL to stdout -->

<property name="show - sqll'>true</property>

<!-- Drop and rc-create the database schema on startup -->

<property narne="hbm2ddl.auto">create</property>

. . . . . -,

. . NOW create a package.structure and develop a Pojo object. . . ' . . .

. . . . ; ,'; . :: . . . : ... .. ... : .:. ,..' ,;: : . .

V@:.xyapt to crate table f i r . ~ . e r s b n with column names as

. (Person - ~D,PERSON - NAME, PERSON . - :. , A G E ) : s ~ & ~ ~ .. . , ... ... develop one P

. . . . . .'> . ,:, .< /. : . . . .

. . .

...

:-:class with all f$se,,attributes ... :

package corn-lara; pu.bIic c1ass;Person . .

{: :.: :I.: . .

' ;;. :::,:~private..l~teger . id; ...

''

..p<i.vate String personName;

private

integer p e r s o d g e ;

. . public int:getId () ( I ; . . . ret',,;* id; , .. ; . 1 I .. -.

. . public void setld (int id) {

this.id = id;.

. . .

. .

public String getPersonName () (

....

. . return personName;

1

public void setPersonName (String personName) {

(12)

this.personNamz = person~ame;

1

pu blic in t getPersonAge () (

return personAge;

>

public void setPersonAge (in t personAge) (

t h is-personAge = person Age;

>

J

>

5. Now develop one hbm file for every Pojo classinone package.

. . : . ". . . .: . . . . >.

-

.---- L-B-1- ally tLaiJlG.

In hibernate with out primary key we can't develo;::':

In h brn file we: want to take care about all attributes fo&ce,&ing . . iCZ .[-. table.

In persons table we want to make PERSON - ID columnas'

-'i.:$i:$'::,

.. ,; 2 .

... . .?. .

autoincrement and primirykey then use id and generator'iag~.i

<?xml version=" 1 .OM?>

<!I?OCTYPE hibemate-mapping PUBLIC

"-//Hibeinate/Hibemate Mapping DTD

3.O//ENW

"http://hi bernate.sourceforge.net/hibernate-mapping-3.O~dtd">

6. Now develop one client programm

(13)

htt~:i!javrteasytosi!~c(?m

package corn-lara;

import org.hibemate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class Manager {

public staiic void main (String [] args)

person pl = new Person

0;

p l .setPersonName ("RAMESH");

p 1 .setPersonAge (29);

N 1. Configuration

Configuration config = new Configuration ();

config-configure ();

//2. Op--- AL - - ---:-- TT'L.

---..

4,.

ell LUG 3GSSiu~i x i I u - s x i s a i i

SessionFactory sf = config.bui1dSessionFactory

0;

Session session = sf.openSession

0;

//3. Start the Transaction

session.beginTransaction

0;

5//4.'Use the Transaction

sessi'on.save (p 1 );

115. Commit the transaction

se~sion.~et.~ransaction ().cornmil ();

116. Close the sessiorr

session-flush ();

session.close

0;

I

7. Now start the database (i.e MySql4) and run the program.

(14)

Updating the record in the database tirouih Hibernate:

Developing a simple helloworldstand alone application by using

-MySql database.

1. Go to eclipse and create one core java related project.

2. Now update the buildpath with hibernate3.jar (i.e core hibernate),

jar fiIes from lib(hibernate dependence .jar files) and the Driver jar

file.

-. .

3. N o w develop hibernate.cfg.xm1 file inside src folder

<?xmI version=' 1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-/Hibernate/Hibemate Configuration DTD 3.0//ENH

"httpri~%ibemate.sourcefor~e.net/hibemate-configuration-3.O.dtd">

<session-factoiy>

<! -- Database connection settings -->

<property name="connection.driver~class"> corn.mysql.jdbc.Driver</property <property naine="connection.url"> jdbc:mysq1:l/localhost/lara</property> <property name="co~mection.username">rootc/property> <property name="connection.password"></property>

<1-- JDBC connection pooi (use the buiit-in) -->

<F:cpei-ty i;ame="comection.pool - sizen> l </property>

<I-- SQL dialect -->

<property name="dialectN>

org.hibef~ate.dialect.MySQLDialect</propert~>

<!-- Enable Hibernate's automatic session'context management -->

<pmperty name="cu~rent - session - context - class">thread</property>

(15)

<property name="cache.provider - classn>

org . hibemate.cache.~o~ache~rovide~lproperty~

<!-- Echo all executed SQL to;~dout.-;> - ..

<property n a m e = " s h o w s q 1 , ~ ~ ~ e < / p r 6 p e ~ > . . ., ,

. : :

. . .

:* .. 7 '. . . . .

<! -- Drop and re-createj..the database' schema on startup -->

<property name="hb~~~~d1.autd~~~uPdate<lproperty . : . . . . . . . . . . <mapping resource="com/lara/Person.hbm.xml'l~ . . . . </session-factory>

.:

'

4. Now create a package structure and develop a Pojo object.

., . . : :,. , . . . . . . .. A:., ... - . . .:,. '.' . i :: . . . / ' :

We want to crate$fable for, person with column names as - - -

. . . .

. . 7 . . <*-: . . . . i.

'

(reis&:-

- ID, PERSON; - N m : P E m O N - ,.>. ., ,,?. .: . .: AGE).So first develop one.Pojo

. . .

. . ; ... .,%..: .. . . ' ,:

class these attrjbufes-$.~~'<.-i ' ?:,.F; : $;.: :. : - : .., . .

. . . . "

.

-.: . - ' . . . . . . - , . . . . . . , ; -7,;. . . > . 2 . . . . . . . . . . . . . . . .. ? . , ! ( % . . - : . : : , . . . . . . . .. :. . ., . . . . . . <.., . . . . . . ., .: - : , . . a > . . . . . . . . . . . . . . : .:..:.. .... : . . pa~kage'com~lara; public claisPkrson . . . . . . . . . . :* j F: .: =:..;; %>, private;qt . . . . _ . . . id; , ... : iprivate<s.txin,g . . . , F: . +.?:.? :..;. personNarne; . . . : . . . . . A . : . . .

f;pA'ilva . . . . . teintiperson~ge; . . . <.. .$. :!-i; , . . . . . ,:. ;:, . Z . ? & , . . . .:: .c.: .$j, i$ ::. ::: :. ... . . . : . . 'i - . . <,. .:, .::+ . . . .. > :. ::<- -<'..'.:' .:... . . . . pu b!lciln$;,get1d . . :1 .. () '( i

:.

; ; i -! . . . . . re.Ku.'&n ..,; . id; : I I : . $.. !:.:,, ;, .'.:

1

. :. . . . . .. . ,

public void setf d ( i n t id) (

this.id

= i d ;

public String getPersonName () (

return persoflame;

1

public void setPersonName (String personName) {

this.personNarne = personName; .,

(16)

1

public in t getPersonAge () (

return personAge;

1

public void s e t ~ e r s o n ~ ~ e (int personAge) (

this.personAge = personAge;

1

1

5. Now develop one hbm file for every Pojo class in one package.

In hibernate with out primary key we can't develop any table.

In hbm file we want to take care about ail attributes for creating table.

In persons table we want to make PERSON-ID column as

autoincrement and primarykey then use id and generator tags.

<propert.j nam e="personName "

co7um="PERSON-NA4\1E11!>

<propefiy name="personAge" coiumn="PERSON

-

AGE"/>

</class>

</hi bernate-mapping>

6. Now develop one client progsamm'. . .

package com.1ara;

-

r

(17)

-u re ~% o~ d aq) unJ pur? (p [b sI C~ a*!) aseqelep aq4 JAeJs MON .L f() uorssa~uadoys = uorssas uorssas ' ()

~G

oJ

~~

Ju

o~

ss

~s

~I

!~

~-~~

uo

~

hrol3e+.po~ssag =JS a)euJaq!H uo!ssas aq* uado *z// :,,,

(18)

Defetinp a recrd through Hibernate'program:

Developing a simple helloworlij stand alone application by using MjrSql database.

1. Go to eclipse and create one core java related project.

2. Now update the buildpath with hfluernate3,jar (i.e core hibernate) ,

jar files from !ib(hibemate dependence:.jar files) and the Driver jar file.

3. Now develop hibernate.cfg.xm1 file inside src folder .. . . .

<?xml version='l.O1 encpding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernat.e.mhematr I ..:; Configuration DTD 3.Gi1Z'pj" . . .. ,

"http:/hibernate:~~brceforge.net/hibemate-configuration-3 . . . . .O.dtdll>

<session-factoiy>

.'.. . ... . . . . .

<!-- Dztabase connection settings -->

<property name="corinecti on.di-iver. - classw>

-- . com.mysql .jdbc.Drive;</property ; . <property name="co~e.ction.url"> . . jdbc:m ysql :/!l o c a l h o s ~ ~ ~ & a ~ / ~ r o ~ e f i ~ ~ ': <property name=llconnection.usemame">root~/pro.pefi~~ <prc)pe~~y name="cormection.pas~word">~/prop~> . . . . . , . :

<!-- JDBC comection pool (use the built-in) -->

<property name="connection.pool - size"> 1 </property>

<!-- SQL dialect -->

<property name="dialect">

org.hibemate.dia1ect.M ySQLDialect</property>

<I -- Enable Hibernate's automatic session context management -->

(19)

<!-- Disable the second-level cache -->

<property n'ame="cache.provider ... -

:

class1'>

org.hibema~k~.~ach6.~o~ache~rovider~/property~ . . . . .

. .

. .

<!-- Echo all executedSQL tojstdout . . . --> -

<property name="show - iql">tiue</property> . .

<!-- Drop and re-create the database schema on startup -->

<property name="hbm2ddl.auto">create~~property>

. -:,. . ... - . . : I < . . . . . . :

. . .

.... :,4. Now create ' ~ i ~ ~ i l i a ~ e , s t r u c t u r e and develop a Pojo object. . . . . . . . . . . . . . . . . . . . .. . . . . ... . : . . . . . , A. ..:, .... ... : ... . . ' - : . . :, '., -l .- . . ... *+. :: +,

... ;Ti, ,.-,..a .+...>.: >.<$G!. g ;?.:>.: , ; ,:i : .:>.: .:

,: . .

. . . ...

....

'...I. We4y.qt to crate table: fd:i+JPetsori . . . . :with~.&l.ixnn names as

. . . . 4... - :..< ... 7 . . >. .> ,...

"' . . . . .: . (Person ~ D & ~ E R S ON NAME, P I Z ~ O N ~ ~ ~ f $ ; ~ b . i $ i ~ ~ t .... develop one Poj

- . Y ;. ;;,,.: . '

..Lr.'..-. i . -

. , . . ..,,.. ! +.:i.:.:. .:; .: ,::!: .. .:'

.,. -:: . . . . .... . . .

i. class with all'~thesi:, ... . ..,.. >.>..:. attributes

1 . : ' , :: .,. - : . . . . i . .- . ' . . . . .

.

... . . . <.. , package c6m;lara; e ..,. ... . . . :- pu$lie r

...

class@e~son ,: ..,. . , .~.<: .r,$ .?..: . . . ~. . . . -. . . .- . . ( !;:!,i:::; . .'L ... _ . . . . . . 4 ...? ... : i ;,.:, ' '. >">. -,, , ... i> !:. .... ... . . -:'.: ... ... ,,:,, -,.,,. *%:'. ...;;. ... ..: 4. :; : )t. zi:5:. . . . v . .... siphlv,ife:,,nty ..-.. ::!. -..:.' d. :... '5 ... .. .: ..- . * . . . . . , '.: ... 5 .;?.. <:.. - , >:

.

" .; ... v ' r. .! >...*.".a .;

.g<!,

: ,f5 . :?.;<; ... p m ~ a t e ..,,; ,:: !:' .. String:per'soiame; . . . . ... .. .>. . . < ...

private: i.nt pers&Age;

j;;

I . . . .

. . . ... . h i - ? :.;: _ I . , ... . . . . . . G&:,. , ! < , ...: ' \ . . ,<.' > i ..: : . ,.. . . . . . I . . public in t @ f f ..:: _I d () ( ..:: . . .,: . p . :?.,..; ,.: .. :... '..- : . . . :. , i,? , .: . ; retum:id; , i:.; .< ' ,., . . . > . . i . . . -

public void setId

(iii

id) (

. . . . thisid = id; : i . :. .; . "

1

5 : . . . ,,

public String getPersonName () f

return p e r s o d a m e ;

1

(20)

public void setPersonName (String personblame) { this.pe~-sonName = personName;

1

public in t getPersonAge ( return personAge;

1

public void setPersonAge (in t person Age) {

this .person4ge = personAge;

1

. .

5. NOW develop one hbm file for every Pojo class

in

one package.

In hibernate.with out primary key w e can't develop any:table.

. , In hbm file we want to take care about all attributes for creating table.

In persons tablewe want t ~ - m a k e - ~ E R S o N - ID column as

autoincrement and primarykek2jihen:useid ... , . . . . ... and generator tags..

1 !i' . . ' , ,..:.: . . . . . i > , . . 1 . . . ! .> :,. .?; " % . : : .i 4;. i . .. . .' .. .. . _ .. <?xm] version="l:.o"?> ,. . . . ..:i . . :.. . . . .

<!DOCTYPE hibeinate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3 .O//ENV

"h~:/hibernate.sourcefoge.netkibemate-mapping-3.~.dtd11~ <hibernate-mapping>

.. . . .

<class name=~~6m.lara.Person" table="PERSONS">

<id name="i& co]umn="PERSGN - ID">

<generator class="native"/: </id>

6. Now develop one client programm

(21)

package corn-Iara;

import org.hi bernate.Ssssion;

import org.hibernate.Szssi~nFactory;

import 0rg.hibernate.c fg.Configuration;

public class Manager (

public static void main (String

[I(

args)

Person pl = new Person

0;.

p l .setPersonName ("RAMESH");

pl .setPersonAge (29);

11 1. Configuration

Configuration config = new Configuration

0;

config.configure 0; . . .. . . . . . . , . . . . .... . .

';112. .ii)'fien the session Hibernate

. .: .. . : .

~ e s s % n F a c i o r ~ ~f=~config.buildSessionFactory

0;

. .

. .

, y,< .;

.. . . . . .. . .. . . . . Session session = sfopensession

0;

< .

I:. 113. Start the Transaction

*. ~ 'Person pl = (Person)session.ioad(Person.class, new

:. ... . . .. . .. . . > . . . :hteger(id)); - . .. .. : . . . , . .. .. . ., . . . . ., . . . . . .

. , . i . , . . . . //.1.;~;& the Transaction

. : . . .;.: ..

. .

~ .:..

7

. . . ses$i&.de~ete(~l);

. ..

115.: Commit ;., c,..: ...- . the trinsaction

sess~pn.getTransaction~().co~mm~t

0;

//6. Close the session

session-flush ();

session.close ();

System.out.println(" Deleted a record from table.");

1

1

(22)

oram. 7. Now start the database (i.e MySql4) and run the pro,

How to develop in web-app: . . . . . .

. . . . . ., .

,t, : .

In this application we are using and we want to create table

. * , , .

for PRODUCTS with columns ., . .

PRODUCT NAME,PRODUCT - PRICE,PRODUCT QUANTITY and

...

< ? ? ; .,-

PRODUCTID.

,t ... .. .. . . . . .

i.. ..I.

and we wanTio insert,delete and edit the already stofedfecord. . .

. . . .

1. Copy all relavent jar files(i.e corehibernate-jar,

'

hibernatedependence-jar files, driver.jar file) in to- the "lib" folder

of our web:application,

2- Now develop hibernat6.?fg.pfilhb . . . "src" folder . . 2 ' ' ' '2.. .. . . . : . . : ! ; :: ... I - . . . . . . , . . ...:... . , . . . . . . . . ' - - . . . . . . . . . . . . I : . .. ,.. . . '. . - . . *; !. > . . . . .. i . . .: ; ;, :; ;:! .?: ,>. :, ,

<?xml version=~~1.O1 encoding='utf-8'?> :i... 'I . ..: . : .

I , .:- . . . . . .

<!DOCTYPE fiibete-configuration PUBLIC . . . . , . . .

"-//Hibemote.Mibemate Configuration DTD ~ . o / E N " " h ~ p : / h i b e m a t e . s o u r c e f o r g e . n e t / h i b e ~ o n - 3 - O . d t d t 1 > . , ,.. ~. > ... <hi bemate-.configui&ion> . , : . .:+ . ., . . . . . . . <session-factory> . , :.... .. . -: . . . .

<!-- Database co.mection settings . . . . --hi: : . . . < ; ' . :. t l " : - <property name=ttconnection.driver~ - i ~ l a s s : . ,: ?. .,,: .;, ::,,:.:. .. .?!. .> -:., :. . . '... sb: :I . - com.mysq1.j dbc.Driver</piopei-ty> . ., >.. . . . . , ., <property name="connection.url"> dbc:mysql://localhost~lara~/property> <property name="connection.username">root</property> <property narne="connection.passwo~></property>

<!-- JDBC connectioi~ pool (use the built-in) -->

(23)

<!-- SQL dialect ->

<property name="dialectn>

o r g . h i b e r n a t e . d i a l e c ~ ~ ~ ~ i a l e c t ~ / p r o p e r t y ~

<!-- Enable Hibernate's automatic . , session context management -->

<property name="cu~ent -

siiii&L:

. . . .

.-

. context . class">thread</propeky>

. . . -

.r ,::; -

. . . ' . , .

< < , . .:

<!-- Disable .the seCdnd-Jevel cac&$

-*,.

. . . ... , . .

<property narne="cache.provider class#3; :

. . - . .; .,.; .. * ..:.: ; -- .. , .-. :org.hibernate.cache.NoCacheProvider</property~ . . . 1 . . . . . . . % . .... . . . . ...

<!-- ~ C h b . . all execut~d~SQL to stdout --> . .

~property~name='show sqln>true</property>

:. . . . : -

. . . . .

-. <!-- ~ r o ~ ; & d . . . . re-create the database schema on startup --.>.,i..

<property n i ~ ~ = : h b ~ 2 d d l . ~ ~ t 0 " > ~ ~ d a t e < / ~ r 0 ~ e ~ > . . .

. . .

4.:::

. . .

. .

3. N.ow:create on$,package . . . structure in "src" folder and deveiop one

:., ... :. .-.. . . . . :: . . . . .I?:, .... Pojo

.c!aGsL;

. .r .... , . ..:". ,;: At?. $ y<.:. .. .>. . . . :. . . . . . ... . . : .?.g;:::p,a ,. y ..:; .?.., c b ' @ com,!ara; . . . :., . .... .... .. ..... : : 3

.

7 : . . . ....

---

: :. - . C 2.. A :... .<l . . : . . ) . . . . -... . . . . ..: ,-, . . . :: : . . . . ..,,,> ;... . . . . ... . . . ; .,, ,:. ' . . . ,:. v- :

? . . . pij

ljJib.

.:class 'Pi.odu&:~.:; ' I , . . . . . . " !

. . . . ... . . . . . . ,,, ,.. ( -,?.:: <

:.:;!

, - . ;, : . .., ir; ... * , A :: j.:,.. : :: . . . . 5 . . ; .: . : . . . . . . . I

private int id;

-

.< :.:. . . .i. "\. ' .:,.. :I.: .

; ,

> . .

priva*g~tring productN&e; ,' ': I

priva&:dou ..%: ble product~~ic6i , . '

-. private int pro,ductQuantity;

.'< .,'; . , . . ::2: .... ,... . . : . . . .. int get~a(l'(.:-

5

. . . . ' r .' ;' return id;' ' .;.: .$

,

. . .

1

. . : ' ,. r

public void set~d(int id) (

(24)

1

public String getProductName() {

return pi-oducWame;

I

public void setProduct~ame(String productName) (

this.productName = productldarne;

public double getProductPrice() {

return productprice;

1

public void setProductPrice(dou ble productPrice) {

this-productprice = productprice;

1

public in t getProductQuantity() ( retu rn productQuantity ;

1

. . . . . .. .; , ... . . : i:. .. ..,, .... > 3 . '~ : ,<> ...' ;. ;.

public void setProductQuantity(in t producfQuantity) $, (

,

Y:'!

this.productQu2ntity = produ~tQuantity~.,~ ;'; .,

1

1

4. Now develop hbrn(Product.hbrn.xrn1) file for every Pojo ". class.

.. : .

',. . .

2 . . .

<?xrnl version=" 1 .On encoding="UTF- 8"?> ... . . : ., .. . . G .

: .,: .

<!DOCTYPE hi bemat e-mapping PUBLIC . .. , . , . .?. .>.: ::. .

.- .

.?i, .

"-/Mbernate/Hibernate Mapping DTD 3.O//ENW :.,.,. 2t.,t! >

"http:i/hibemate.sourceforge.net/hibemate-rnapping-3 .~.dtd":'

(25)

5. Now develop one Jsp file and use it

add.jsp page is-for inserting the values into the table.

. . . .

, .; - / " ,.,.

. . . : ,. . .

: ;:ce

kdit.jsp :. . . .<.., page updating the already existing record.

. .< . :.: ..;. ..: ,?: . 2 .?'. c, i?!.:;::.: . . . .<:<,;; &:: ... : .. l . ' ' ",$, ..:: ... , : ... .::;x; .*.f?i *,.: . ,>. ... : <..,,

-.

L .>,;;c:t,,+, ? ed it.i$+;, .

.;.<:;;;:

';. ..:&p[:$: ..: : ... ... a. .. .:. <..,,>> *.A, i .: .ii ,, ;i. <\ ' . . . ,:,>..

delete.jsp is for deleting the record from table.

(26)

delete. i s p

3. Develop servlets for every jsp pages.

Insertsewlet. java . . . . . . . . . 2 : . . . .=.. . . . .. . . . . . p c k a g e com.lara; . . . . 8 . . . . .: .... : . . . . import j ava.io.IOException; .. i m p o r t j a v a . i o . ~ r i n t ~ r i t & . . . . . <..,. . . ;,. . . , . . import javax.servlet.~~rv~~t~~~e'~ti6n; . . ..< .,..- .>*. ,.. . . ....:.. ...: . . ... ; . . im poi~j;avax.servlet.httPP~tt~~~,irt-let~e~~est; . . . . r ' . import jz~ax.sen~let.htt~.~ttp~ervlet~es~onse; .. ..: . . . . . . . : . import org.hibernate.Session; . > . . ... . . . . . . .

import orghibemate. SessionFactory ; .. . ~ . . . . .

. . i. . .

import org.hibemate.cfg.Configuration; . , . . . . . . .:

.I '.:I

..

public. c l a s s ~ , ~ n ~ e r t ~ e r v l e t extends javax.servlet.http.~ttp~:e&let ....

implements javax.servlet.Servlet ( . .

static final ,long serialVersionUID = 1L;

public ~nsert~ervlet() ( - 1,

. . . .

super();

. . .

i . . .

protected void d o ~ o s t ( ~ t t ~ ~ e r v l e t ~ e c @ e s t request,

HttpServ1e.tResponse response)throws . . ServletException, IOException

c

1

String pName = request.getParameter("productNamelI);

String pPrice = request.getParameter("productPrice");

String pQty= request.getParameter("productQuantity");

Product pdr = new Product();

(27)

Configuration config =,new Configuration(); config.configure0;

SessionFactory sf =~config.buildSessionFactory();

Session session = sf.openSession();

session. beginTransaction(); -', isession. close(); . . package com.l$.a;,~::: ... : .+>. ;,,:, >;.!

-.

. . r l i ..: .$..:<;..: ' ,:;. . . . . . : . . . . <..?*. : ..,:: ..;..::... ... ..; . .# .;.; C.; - . ,. : .':.' .: . . im p o r t ~ 5 ; ~ ~ ~ ~ o ~ I O E x c e ~ ~ o n ; ... . ... . . . ... . . . . : , . I . . .

import j a + & i o . ~ : ~ i n t ~ r i i k i ; . . .

zy..:

. ,.., ....

import javax.~~$$51et.~ervlet~x~~,<tion;

import javax.s~&lkt.http.~ttP~enil~t~equest; ... .: ;.

import jstvax.servlet.http.HttpServIetResponse;

import org.l?i

-

bernate.Session;

import org.hibemate.SessionFaciory ;

import org.hibemate.cfg.~onfiguration;

public class UpdateServlet extends javax.servlet.http.HttpServ1et

implements javax.servlet.Servlet {

(28)

static final long serialT7ersionUlD = 1L;

public UpdateServlet() {

super();

1

protected void d o ~ o s t ( ~ t t ~ ~ e r v 1 e t ~ e ~ u e s t request,

HttpSepletResponse response) throws ServletException, IOExcept ion

C

String id = request.getParameter("idn);

String pName = request.getParameter("productName");

String pPrice = req~est.get~ararneter("~roductPrice");

String pQty = request.getPararneter("productQuantity1');

Configuration config = new Configuration();

config.configure();

SessionFactory sf = config.buildSessionFactory0;

Session session = sf.openSession();

session.beginTransaciion();

Product p 1 = (Prociuct)session.load(Product.class,

Integer.parselnf(id));

Printwriter out = response.getWriter();

out.println("PR0DUCT UPDATED"); out.println("<br><a lirePindex.jsp>HOME</a>"); out.close();

1

1

Lara Technologies 080-41310124

(29)
(30)

PrintUTriter out = response.getWriter(); out .println("PRODUCT DELETED");

out.println("<br><a hreeindex.jsp>HOME</a>");

-.

4. Now 'start the data base(i.etMySq14) andllrun the "index.jspn. ..

.. ..

. . . . . .

? . . '. -

One m o & : ~ a ; a m ~ l e .. for how to devlop hibernate $$$in ,... web-app . . by

doinp all the o ~ e ~ ~ t i ~ ~ s iSe izsert ~ F d a t z , ! i s $ , s ~ ~ ~ ~ & ~

. - . .. . , '; ..

In

. . this application we are using Oracle1 0g database and we want to

create table for ADDRESSES with column names as ADDRESS-ID, .

ADDRE~~S HOUSENO; A D D ~ S S .

;

STREETNO, ADDRESS - CITY,

ADD$&~sT~~E,

ADDRESS

- CO-WRY,' .. . and.,

. , , . . ADDRESS,-PINCODENO. - . . . - . . . ! . . ,. hiberna te.cfg.xm1 , . ! .. ... . . <?xml:~y~~sion=' 1.0! &icoding='utf-8'?> . .. .

<!DOCTYPE hibernate-configuration PUBLIC

"-/Hi bernateMi b e r n a t e ~ o n f i ~ u r ~ t i o n DTD 3 .O//EN "

" h t t p : / / h i b e r n a t e . s o u r c e f o r g e . n e t / h i b e ~ a t i o n - 3 .O.dtdn>

<I-- Database connection settings -->

<property name="connection.driver~class">

oracle.jdbc.drive~OracleDriver~/propert~> <property name="connecti on.url">

jdbc:oracle:thin:@Iocalhost: 1 521 :XE</propedy>

<property narne="connection.usernarne">system<iproperty>

(31)

<!-- JDBC connection pooi (use the buiit-inj -->

<property name="connection.pool - size">] -4property>

<!-- SQL dialect -->

<property narne="dialectn>

org.hibernate.didect.OracleDialect</property>

<!-- Enable Hibernate's automatic session context management -->

<property name="current - session - context - class">thread</property>

<!-- Disable the second-level cache -->

<property name="cache.provider - classH>

org.hibernate.cache.NoCacheProvider~/property>

<!-- Echo all executed SQL to stdout --> .. .

<property name="show - ~ ~ l ' ' > t r u e 4 ~ r o ~ e r t y > . . .

.. . .

. . . . . . . . . . , .

<!--

and

. ., . re-create the ditab&e schema . . . . . ..o,n!startup . ... . -->

~prope~y?:~n~e="hbm2ddl.auto1~>upda~e</'p~op~rty>

. .

. .

package com.lara;

public class Address

{ ...

private Integer Id;

private String houseNo;

private String streetNo;

private String city;,

(32)

private String state; private String country;

. .

PI-iva te long pinCodeNo; . .

public Integer getId() { . :

return Id;

1

public void setId(lnteger id) ( .. .: .

Id = id;

1

pu b lic String getHouseNo() ( .. .

.

return houseNo;

1

public void setHouseNo(String houseNo) {

this. houseNo = houseNo; .. .. %. . . .

>

* . : ..

. ..

public String getStreetNo0 ( . . . .

public String getcity() (

return city

1

.public void s&tsC:ity (String city) { ,.

this.city

-

city;

>

'

public String getstate() {

retu rn siate; .;

public void seiSizte(String state) {

this-stzte = state;

i

public String get~ountry()'{ return country;

>

public void setCountry(String country) {

this.country = country;

(33)

public long getPinCodeNo0 (

return pinCodeNo;

1

public void setPinCodeNo(1ong pinCodeNo) (

this-pinCodeNo = pinCodeNo;

1

1

j

<?xml version=" 1 .On encoding="TTTF-8"?>

<!DOCTYPE hibemate-mapping PUBLIC

"-//Hibematemi bemate Mapping DTD 3 .OiIIEN1'

"http:/hibemate.sourceforge.net~hibernate-mapping-3.O.dtd">

- .

In hbm file we are not giving any column names for property tag then it

(34)

add-jsp is for inserting the values into the ADDRESSES table. add.isp

<body>

<form action="lnsertServlet" method="post">

HouseNo:<input type="text" name="houseNo"><br>

StreetNo:<input type="textW name="streetNo"><br>

City:<input type="textU name="cityM><br>

State:<ir,put type="textW name="statenxbr>

Country:<input type="textU name="countryl'><br> PinCodeNo:<input type="textn

name="pinCodeNol'><br>

<input type="submitU value="ADD ADDRESSv> </form>

</body>

search.jsp is for serrrching the particular record in the table

.

, , by

selsecting the coIumn names and giving the text to search. search.isp <body> <folm action="ListSei-vlet"/> SearchCriteria: <select name="searchCriteria"> <option value="id">AdressId<loption> . coption value="houseNo">HouseNo</option> <option value="streetNo">StreetNo</option> <option value="city">City</option> ' <option value="state">State</option> <option value="country">Country</option> <option value="pinCodeNo"> PinCodeNo</option> Lara Technoiogies

(35)

</select><br> SearchText:

<input type="textl' name="searchText"> <input type="submit" value="Search"> </form>

. . . </body>

InsertSew1et.java is for inserting the values into the table. If we want to

~.

insert the servlet then . . . . . we to :call save0 by passing the object.

. . . .,r . .

~

~

~

e

.' : .::.

~

~

~

~

~

i

&

i

~

~

~

~: . :.., . : .< . ,:. . , , . . ,:: .. .<' package cok.lara; . . ... import j a v a ~ ~ . ~ ~ ~ x c e ~ t i o n ; import java.i&P*int~rite~ . . . import ja~ax.senile~~~ervlet~xce~tion;

.

. .... ... . . < .> ,;. .,,.; .J . . . I* ..'I' . . . .< :

.-::

. . . ~import~,.javax.servle~littp;NttpS.ervletRequest; % . . . . , . :

..

. . . . . . : . .‘ '

-

~m por~~~~y.gx.servlet-.http.~ttP~ewlet~esponse; . . . . . .. ;.:z!:..* :.. ' . . . . . . . ; . . . . ! im p o k t ~ ~ g

' ~ ~ ~ i b e m a t e . ~ e s s i o + , ~ C ~ ~ r y ;

: . . . . ...;.

.-....;i~.;:t-..:,:.

- . . . . . . .~ . import org;hlp.emate.cfg.~onfig&ition;. ' .. . . . .. ::. .!. .-.I . . . .,-., 6 : .:>; . . . y : .,.import org.hikieqate.classic.Session; . . . . . ' . I * > 3 . .> >.

- , .,:.

.r

. . public

_

_

. class InseASewlet ; :, :, ...:. extends javax.serv1et.http.HttpServlet

'implements . . javaxi$ervlet.Servlet {

stati&$inal ;. i,:t.;.

".

long & & i a l ~ e r s i o n ~ ~ ~ ,.. .:, .:: = 1 L;

<p"biic~,nsert&ervlet() (

-- $$~z$* .a>.:. rx B 7 :

.qg .*gj.y..t- 3.%&,, p e+l@;$$ , . . , . . - I :.t< .-

.

. . - . .

3.a;T<$rV 3.. ; ... .*. 2: . . . .I.. :ry .:..:. .A, .I

.... ) .** .. "6 >??, - i , . !.%- <>;.;. z . :. .;. * . .. . ; : , ., *:;$ ,:. ..< :.:. <..? :.. ... .: ... . '.,?'.. . I-".

protect6djvoid . c .? doPost(H~p.Se~IetRequest request,

HttpSer:!etRespoii$ci 1. response)'th . . . . rows ServletExcepti on, IOException

. ,. . I , . 1 String houSe~o-7e~uest.get~irarneter("house~o"); String ~treetN~equest.getParameter("streetNo"); String city=request.getPararneter("city"); String state=request.getParameter("state"); String country=request.getPara,aeter("country "); string pinCodeNo=request.getPararneter("pinCodeNo");

Address adr=new Address(); adr.setCity(city);

(36)

Configuration config = new Configuration();

config.configure();

Session session = sf.openSession();

session.getTransaction().commit(); ~ . . !. . : . :.' . . . . ;.. !. . . session. flush(); ::, :; ' ..: . , , :: .:>r ,. < . . .

;.

. . ... t i . . .. .... .. % . . session.close~; .: . .. .., : ..> ., : !*

Printwriter out = response.getWriter(); . . . , . *., . ...

O U ~ . ~ ~ ~ ~ ~ ~ ~ ( " A D D R E S S SAVED");

UpdateServlet.java is for editing the particular record in the table. If we

want to update the record then we want to call saveOrupdate() . , by

passing the object. UpdateServIet-iava package corn-lara; import java.io.IOException; import java.io.PrintWriter; import javax-sei-vlet.ServletException; import javax.servlet.http.HttpServ1etRequest; import javax.~ervlet.http.~tt~ServletResponse; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.classic.Session;

public class UpdateServlet extends javax.servlet.http.HttpScm1et

implements javax.servlet.Serv1et

(37)

static final long seriali/ersionUlD = 1L;

public UpdateSer\.iei() {

supero;

1

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

{ String id = request.get~ararneter("recordld"); String houseNo=request.getParameter("houseNo"); String streetNo=request.getParameter("streetNo"); String city=request.getParameter("city"); String state=request.getParameter("state"); String country=request.getParameter("country"); String pinCodeNo=request.getPararneter("pinCodeNo");

Address adr=new Address();

. .

i

. . Configuration config = new Configuration();

. config.configure();

SessionFactory sf = config.buildSessionFactory();

Session session = sf.openSession();

(38)

Printwriter out = response.getWriter(); out.println(llADDRESS SAVED<br>"); 'out.println("<a hrePindex.jsp1>Home4a>"); out.println("<a href='ListServletl>ListRecordHome</a>"); out-close();

1

1

ListServlet.java is for listing all the records from table. If we want to list

all the records then rve want to use criteria interface or Query

interface. In this application we a r e using Criteria.If we want to create

object for Criteria interface then there is a method createcriteria ()

which there inside the session class.

Eg: session.createCriteria(Address.class); import java.io.IOException; i m p ~ r t java.io.Print'Clrriter; import java.util.list; import javax.servIet.ServletException; import javax.servlet.http.HttpServletRequest; irnpo~j~vax.servl~t.http.~ttP~ervletResponse; import drg.hibernate.criteria; import org.hibernate.~ession~actory; !. import 0rg.hibernate.cfg.Configuration; " import org.hibernate.classic.Session;

p ~ b I i c class L.istServlet e x t e ~ d s javax.serv1et.http.HttpServlet implements

j avax.servlet.Servlet

static final long serialVersionUlD = 1L;

public ListServlet() {

(39)

protected void doGet(HttpServ1etRequest request, HttpServletResponse

response) throws ServletException, IOException

i

Address add= new Address(); . .

Printwriter out = r e ~ ~ o n s e . ~ e t ~ r i t e r ( ) ; , . String sc = request.getParameter("searchCriteria"); String s t = request.getParameter("searchText"); out.println(''<table bord'er='.ll>"); . . . out.println(";=tr>."); . . . . o~t.~&tln("<td>"); out.println("<b>ID</b>"); o~t-println(~:</td>"); out~println(" <td>ll); out.println("<b>HOUSENO</b>"); -. . . . o,ut.println("</td>"); o~t~println(llitd>l~); . . o~t.~iin~ln("<b>~~RE~'l'N~</b>~~); . . .! ...! out.printlnt:y</td>'.');

.

o~t.~rintln~!'<idY); . '. ; :

:~out.print]n("<b>CITY</b>");

. . . :... . - . . . . . . o~~t;printlil("</id>"); .. .. , ., ... . . . :, ,. . . ;:, 6 . &it'< :intln "<td>"). . . - r . . .... ..;::s:. ... >:; *,.

p.:

, ( ... ' .?.!<<>? 7 I

_

o~~j$&tln(l'<b>~~~~~</b>'l); .... .:, . : out:$rini]n(tl</td>"); I ; .. :. ~ut.~rintln("<td>"); : .. ~ u t ~ . ~ r ' i n t l n ( " < b > ~ ~ ~ ~ ~ ~ ~ < / b > ' ~ ) ; :: - . out.prinilG("'</td>''); .'. . . : , .,. ,o;t;ijriniln(!l,<td>'l); . . . . . . . .

o~~println("<b>PINCODENO</b>'~);

., out.~iint]n("</td>;;); .' out.print~hp'</tr>~~); . . i 5

Configuration config = new Configuration();

ccnfig.configure(j;

SessionFacto~y sf = config.buildSessionFactoryO;

Session session = sf.openSession();

(40)

Criteria ctr = session.createCriteria(Address.class)J

ctr.add(Expression.eq(sc, st));

List list = ctr.list();

for(int i=O;i<list.size();itt-) add = (Address)list.get(i); out.println("<tr>"); out.printIn(''<td>l1); out.println("<a href-'DetailedServlet?recordId=" +add.getId()+'">"); out.println(add.getId()); out.println("</a>"); out.println("</td>"); out.println("<td>"); out.println(add.getHouseNo()); out.prin1ln(lf</td>"); out.println("<td>"); our.println(add.getStreetNo()); out.println("</td>"); , out.printIn(l'<td>"); out.println(add.getCity()); o~t.println("<ltd>~'); out.println("<td>"); out.println(add.getState()); out.println("</td>"); out.println("<td>"); out.println(add .getcountry()); out.priniln(":itd>"); out.println(lT<td>" j; out.println(add.getPinCodeNo()); out.println("</td>"); out.println("</tr>");

1

out.println("<ltable>"); out.println("<a href-'index.jsp'>Home</a>"); session.getTransaction().commit(); Larn Technologies 080-41310124

(41)

DetailedSewlet.java is for if we select one record then it want to display

all the co1llmns from the table.for this we want to use load () method

which there inside the session class.

package com.lara; import java.io.IOException; import java.io.PrintWriter; import javax.se~let.ServletException; import javax.servlet:http.HttpServletRequest; import javax.servlet.http.HttpServ1etResponse; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibemate.classic.Session;

public class DetailedServlet extends javax-servlet.http.HttpServ1et

implements javax.servlet.Servlet

staticdinal long serialVersionUID = 1L;

public DetailedServlet() (

super(

1;

1

protected void doGet(HttpServ1etRequest request, HttpServletResponse

response) t h rows ServletException, 1 0 ~ x c e ~ t i o n

String recordld = request.getParan~eter("recorc!Id''~;

Configuration config = new Configuration();

config.configure();

(42)

Session session = si'.openSession(

session.beginTransaction();

Address add = (Address)session.load(Address.class,

new Integer(record1d));

Printwriter out = response.getWriter():

out.println("HouseNo: "+add.getHouseNo()+"<br>"); out.println("StreetNo:"+add.getStreetNo()+"<br>"); out.println("City :"+add.getCity()+"<br>"); out.println("State:"+add.getState()+""); out.println("Countiy :"+add.getCountry()+"<br>");

out.println("PWCODENO:"+add.getPinCodeNo()+"<br>");

out.println("<a href-'DispIayForEdit?recordId=" +add.getId()+"'>Edit </a>"); out.prir~t;~l<";a ;~i.t.C='Se;eteServlet?recordld=" +add.getId()+"'>DeIete</a>"); out.println("<a href-'index.jsp'>Home</a>"); out.println("<a hreFListServlet'>ListRecordHome</a>");

DeleteServlet.java is for deleting the particular record.If w e want to

delete one record then w e want to call the delete0 by passing the object.

package corn-lara; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.hitp.ltittpServletResponse;

.

. nm port org.hibernate.Session.Fac~~~~; Lsm Technologies 056-3!310i24

(43)

import org.hibernate.cfg.Configuration;

import org.hibernate.classic.Session;

public class DeleteServlet extends javax.servlet.http.HttpServlet

implements javax.servlet.Servlet

, static final long sevinlVersionL'ID = 1L;

public DeleteSel-vletO {

seper();

1

protected void doGet(HttpServ1etRequest request, HttpServletResponse

response) throws ServletException, IOException {

String id = request.getPararneter("recordIdI1);

Address add = new Address();

add.setId(new Integer(id));

Configuration config = new Configuration();

: .'; ; -c.onfig.configure(); . . . . . . . ... . . :. . . . .. .;. -.. . _ , . . ~ ~ ~ i o n ~ , a c t o r - y sf = c ~ n f i ~ . b u i l d ~ e s s i o n ~ a c t ~ ) ~ ~ ( ) ;

Session session = sf.openSession();

Printwriter out = response.get'?iriter();

out.println("ADDR.ESS DELETED"); - out.println("<a hre+'index.jsp'>Hor,e<ia>"); out.println("<a href='ListServlet'>ListRecordHome<i'a>"); out.close();

1

1

Lara Technologies

(44)

DisplayForEdit.java is for modifying the particular record in the table. package corn-lara; import java.io.IOException; . . import java.io.PrintWriter; import javax.servl.et.ServletException; import javax.servlet.http.HttpServ1etRequest; * %

import javax-sesvlet. http.HttpSefvletResponse; . .

import org.hibemate.SessionFactory; . . . . ., : . .... .. : ..

import org.hibemate.cfg.Configuration; . , . .. . . . . '.: .

.. . .

impsrt org.hi5e~s~e~clsssic.Session; . . . .

public class DisplayForEdit extends javax.servlet.http.HttpServ1et

implements javax.servlet.Servlet . .

{

static final long serialVersionUID = 1L;

public DisplayForEdiii) {

super();

1

protected void doGet(HttpServletRequest request, HttpServletResponse

response) throws ServletException, IOException

{

String recordId = request.getPararneter("record1d");

Configuration config = new Configuration();

config.configure(.);

SessionFactory sf = config.buildsessio&ctory();

Session session = sf.openSession();

session.beginTransaction();

(45)

* Address add = (Address)session-load(Address.class,

new Integer(record1d));

out.printin("<form action='UpdateSenlet' method='post'>" j;

out.println("<input type='hiddenl name='recordTd' vzlue-"'

+add.getId()+"'>< br> ");

out-print In("HouseNo:");

out.println("<input type='textl name='houseNol value="'

+add .getHouseNo()+"'><br>");

out.println("StreetNo:");

out.println("<input type='text' name='&eet~o' value="' +add.getStreetNo()+"'xbr>");

out.println("CityW);

out.println("<input type='textt name='cityt value="' +add.getCity()+"'><br>");

out.println("StateW);

out.println("<input type='textt name='statet value="' +add.getState()+"'><br>");

out .println('lCountry");

out.println("<input type='textl name='countryl val?le="'

+ad8get~ounhy(+"'><br>''); out.println("PinCodeNo:");

out.println("<input type='textl n a m & ' p i n ~ o d e ~ o ' value="'

+add.getPinCodeNo()+"'><br>"); out.println("<input type='submitt value='UPDATJV"; ~ut.~rintln("</form>");

. . . .

...

. . . . .... . .

What are all the algorithmsforattribute "class" of "generator "tag of "ici"

tag ?

9 The types of algorithms are:

1. hilo 2. seqhilo 3. uuid Lara Technologies

References

Related documents

Such a collegiate cul- ture, like honors cultures everywhere, is best achieved by open and trusting relationships of the students with each other and the instructor, discussions

As a result of sex differ- ences in CRF1 coupling to G s (female bias) and β-arrestin 2 (male bias), corticotropin-releasing factor (CRF) released dur- ing stress can engage

Our Supplier Innovations Showcase allows you to engage railway professionals through our magazine, podcast series, virtual event series, newsletter, and a website channel dedicated

Optimized for other works are websites are references italy in your favorite websites to make great way to italian as the code.. Innovation across italy and investigations live

A hexagonal lattice produces five distinct wallpaper groups that are different from those produced by a parallelogram, rectangular, rhombic or square lattice: p3,

This document is intended to serve as a tool for health care providers to communicate known or potential radiation risks associated with paediatric imaging procedures, to

• “Acceptance tests” are defined by the customer and executed to assess customer visible functionality.. Dynamic Systems

There are three main com- ponents: (i) the schedule describing the sequence of node activations and the timings of the messages between the nodes, (ii) the asynchronous state