Thursday, July 10, 2008

Spring-Hibnate-Struts config

Spring (Is a Factory)

1)

-Struts is a web application framework

-Hibernate is a ORM framework

-Spring is an Integration framework

2) Spring allows us to develop business logic layer in a light weight manner (independent from standalone, web, distributed (RMI/CORBA), business applications (EJB)s and inter-operable applications (WebServices). That means the business logic implementation must not contain session,config,context etc objects and the logic should not use any model/ORM framework objects directly

3) Light weight business logic component development

-When business logic is implemented in EJB (SessionBeans) each method of EJB is accessed from container code (container provides middle level service implementations such as TX, persistence, security etc). Such business logic methods of EJB cannot run outside the container / application server process. Hence EJB business logic methods are called as heavy weight business logic methods due to tight intergation with container code.

-Spring says the business logic methods can be implemented without service layer. Hence these bean implementation can run on standalone, web and application servers. As and when these services are required the same bean can be executed on application server and required services can be injected into bean method implementations without effecting the code.

4) Dependency Injection (Injecting dependent objects)

-During business logic method implementations in J2EE components (servlets used to often/frequently perform lookup() operations on container to obtain DataSource/Connection pool objects and EJBObjects, EJB also does the same). Hence those components are as earlier stated as heavy weight components.

-Spring recommendation is to avoid JNDI lookups and various component object creations in business logic methods of Spring Beans. Spring says inform all the required/dependent objects in xml document, spring container reads, when the business logic component is instantiated container create and passes all the required objects into bean through constructor injection or setter injection

Spring installation

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

-Download Spring software ZIP file

1.2, 2.0, 2.5.4

-Extract it into local drive

dist - all the jar file

docs

api

MVC-Step-by-Step

reference

html_single

pdf

lib (spring addl libraries)

-Write a "ENV.bat" that includes all spring libraries in CLASSPATH

SET SL=D:\spring-framework-1.2\dist

SET CLASSPATH=%CLASSPATH%;%SL%\spring.jar;%SL%\spring-aop.jar;%SL%\spring-beans.jar;%SL%\spring-context.jar;%SL%\spring-core.jar;%SL%\spring-dao.jar;%SL%\spring-hibernate.jar;%SL%\spring-jdbc.jar;%SL%\spring-mock.jar;%SL%\spring-orm.jar;%SL%\spring-remoting.jar;%SL%\spring-support.jar;%SL%\spring-web.jar;%SL%\spring-webmvc.jar;D:\spring-framework-1.2\lib\jakarta-commons\commons-logging.jar

-Write a simple spring bean component to test setter and constructor injections performed by Spring Container

E:\active\spring\dj1\

- Hello.java

- beans.xml

(spring container reads this file, beans are configured here)

- HelloClient.java

(Instantiates spring container, passes XML doc into it and access bean object(s))

// Hello.java

public class Hello

{

String name;

public Hello()

{}

public Hello(String n)

{name=n;}

public void setName(String n)

{name=n;}

public void sayHello()

{

System.out.println("Hello : "+name);

}

}

beans.xml (spring DD file, spring container reads this file)

Active

NET

// HelloClient.java

import org.springframework.beans.factory.*;

import org.springframework.context.support.*;

public class HelloClient

{

public static void main(String rags[]) throws Exception

{

BeanFactory f=new FileSystemXmlApplicationContext("beans.xml");

Hello h1=(Hello)f.getBean("h1");

h1.sayHello();

Hello h2=(Hello)f.getBean("h2");

h2.sayHello();

}

}

Lifecycle of Spring light weight container BeanFactory

-Like previous J2EE containers (Servlet, JSP,EJB), Spring container also provides 2 services

i) Resource management service

--includes when to create and destroy object and how many objects of the class want to be created etc comes under this service

--For this spring uses two resource management techniques one is "singleton" and other one is "prototype - new object for every request"

--to specify this in bean tag we must include singleton attribute assigned to "true" or "false"

ii) Lifecycle service

--Lifecycle methods are used by container/runtime process to inform object creation state and destruction state to component/bean/class

-Old J2EE containers force components (servlet,JSP,EJB) to implement container complaint/predefined lifecycle methods (init(), destroy(), _jspInit(), _jspDestroy(), ejbCreate(), ejbRemove()). But spring container says component can implement user defined methods and if those methods are specified in tag with two attributes one is init-method="setup" and other attribute is destroy-method="teardown"

The lifecycle of object creation is

- As soon as we request beanfactoy.getBean("h2"), spring container instantiates bean with default / no arg constructor (in setter injection) or parameterized constructor during constructor injection)

-If setter injection is required set method(s) are called on bean instance

-User defined init-method

-and then gives bean ref to client

-as soon as client requests on bean methods are completed, before garbage collecting bean instance container invokes user defined destroy-method

Apart from resource management and Lifecycle service, spring container also provides some extra information to bean instance

Do one example Runtime polymorphism in Spring

1) Open MyEclipse

2) Create Java Project Name: stud_hib_dao_2

3) Hibernate capabilities

-Right click on the project-> MyEclipse-> Add Hibernate capabilities -> repeate the same for Spring capabilities

-Choose Hibernate version-> Next-> Next-> Uncheck Specify DB connection details-> unselect Create SessionFactory class->

4) Spring capabilities

Spring 1.2 Core libraries

Spring 1.2 Hibernate 2 libraries

Spring 1.2 Misc libraries

click on Next-> Change the spring config file name to "beans.xml-> unselect Spring config to hibernate config file-> Finish

5) Add new Java class

Name: Student

public class Student implements Serializable

{

private int sid;

private String sname, email, mobile;

Right click anywhere on the class and choose "Source", "Generate getters and setters"

public String toString()

{

return sid+" "+sname+" "+email+" "+mobile;

}

}

6) Student.hbm.xml

Copy this file from hib_hql_2 project

remove Batch and Course classes configuration from this file

7) Add new Java interface

Name: StudentDAO

click on Finish

public interface StudentDAO {

public void insert(Student s);

public Student select(int sid);

}

8) Add new Java class

Name: StudentDBDAO

public class StudentDBDAO implements StudentDAO

{

DataSource ds;

public void setDs(DataSource ds)

{

this.ds=ds;

}

public void insert(Student s)

{

try

{

Connection con=ds.getConnection();

Statement stmt=con.createStatement();

PreparedStatement pstmt=con.prepareStatement("INSERT INTO student VALUES (?,?,?,?)");

// PK generation

ResultSet rs=stmt.executeQuery("SELECT max(sid) FROM student");

int sid=0;

if(rs.next())

{

sid=rs.getInt(1);

}

sid++;

// insert record into table

pstmt.setInt(1, sid);

pstmt.setString(2, s.getSname());

pstmt.setString(3, s.getEmail());

pstmt.setString(4, s.getMobile());

pstmt.executeUpdate();

}

catch(Exception e)

{System.err.println(e);}

}

public Student select(int sid)

{

Student s=null;

try

{

Connection con=ds.getConnection();

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("SELECT * FROM student WHERE sid="+sid);

if(rs.next())

{

s=new Student();

s.setSid(rs.getInt(1));

s.setSname(rs.getString(2));

s.setEmail(rs.getString(3));

s.setMobile(rs.getString(4));

}// if()

}// try

catch(Exception e){}

return s;

}

}

// StudentHibDAO.java

public class StudentHibDAO implements StudentDAO

{

HibernateTemplate ht;

public void setHt(HibernateTemplate ht)

{ this.ht=ht; }

public void insert(Student s)

{

HibernateCallback hc=new HibernateCallback() {

public Object doInHibernate(Session ss) throws HibernateException, SQLException

{

ss.save(s); return null;

}

};

ht.execute(hc);

}

public Student select(int sid)

{

HibernateCallback hc=new HibernateCallback() {

public Object doInHibernate(Session ss) throws HibernateException, SQLException

{

return ss.get(Student.class, new Integer(sid));

}

};

return ht.execute(hc);

}

}

// StudentController.java

public class StudentController

{

StudentDAO sdao;

public void setSdao(StudentDAO sdao)

{

this.sdao=sdao;

}

public void addStudent(Student s)

{

sdao.insert(s);

}

pulblic Student getStudent(int sid)

{

return sdao.select(sid);

}

}

beans.xml

sun.jdbc.odbc.JdbcOdbcDriver

jdbc:odbc:oracledsn

active

activenet

net.sf.hibernate.dialect.Oracle9Dialect

true

Student.hbm.xml

// StudentClient.java

public class StudentClient

{

public static void main(String rags[]) throws Exception

{

BeanFactory f=new FileSystemXmlApplicationContext("beans.xml");

StudentController sc=(StudentController)f.getBean("sc");

Student s=new Student();

// s.setSid(5);

s.setSname("Lambu");

s.setEmail("lambu@lj.com");

s.setMobile("9899999999");

sc.addStudent(s);

Student s2=sc.getStudent(5);

System.out.println(s2);

}

}

Spring Web MVC Architecture

1) web.xml

2) Spring Controller class

3) dispatcher-servlet.xml

4) Login.jsp

5) LoginSuccess.html

6) LoginFailed.html

1) Open MyEclipse

-File-> New-> Web Project->

Name: spring_web_3

Add Spring capabilities

Include Spring Core & Web libraries

Spring config file: dispatcher-servlet.xml

Make sure to place dispatcher-servlet.xml in WEB-INF folder

dispatcher

org.springframework.web.servlet.DispatcherServlet

dispatcher

*.htm

2) SpringController class/ business logic class

spring_web_3

src

beans

LoginController.java

public class LoginController implements Controller

{

public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception

{

String user=arg0.getParameter("user").trim();

String pass=arg0.getParameter("pass").trim();

if(user.equals("active") && pass.equals("activenet"))

return new ModelAndView("./html/LoginSuccess.html");

else

return new ModelAndView("./LoginFailed.html");

}

}

3) dispatcher-servlet.xml

4) Login.jsp

User

Pass

5) LoginSuccess.html

Login Success

6) LoginFailed.html

Login Failed

http://localhost:65535/spring_web_3/Login.jsp

dispatcher-servlet.xml

lc

./

.html

// LoginController.java

return new ModelAndView("LoginSuccess");

Flow of Spring Web MVC

1) While developing Spring Web MVC application DispatcherServlet class must be configured in web.xml file with the url-pattern *.htm

2) Each form submission made from client must contain action path suffixed with .htm

3) Such requests are submitted to DispatcherServlet

4) DS instantiates SpringContainer (dispatcher-servlet.xml)

5) lookup for the bean named "urlMapping", resolves "action path" with "bean id"

6) lookup for the bean with id

7) Instantiates Controller class, invokes setter injection methods and finally invokes handleRequest method

8) As soon as SpringController returns ModelAndView object

9) DS resolves prefix and suffix names of view, prepares fully qualified name of view and redirects respective document to browser

Struts-Spring Integration

1) Struts-Spring integration is required to achieve IoC in Struts

2) There are two ways integrate Struts with Spring

a) extend Action class from ActionSupport, configure Action class in s-c.xml, obtain XmlWebApplicationContext object in execute() method and access beans from spring container

b) Keep Action class remain same (extend from Action,DispatchAction class of Struts), configure it in spring xml file, redirect every form request coming to struts framework to Action class via DelegatingActionProxy. Passing request to Action class via DAP will acheive Dependency Injection on Action class.

Struts-Spring intergation steps

spring_struts_4

src

beans

NewStudentAction.java (2) , Student.java, StudentDAO.java, StudentDBDAO.java, StudentHibDAO.java, Student.hbm.xml

WebRoot

NewStudent.jsp (1)

StudentSuccess.html (1)

StudentFailed.html (1)

WEB-INF

web.xml

struts-config.xml (3)

action-servlet.xml (4)

NewStudent.jsp

<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="h"%>

Name

Email

Mobile

StudentSuccess.html

Insert Success

StudentFailed.html

Insert Failed

// NewStudentAction.java

public class NewStudentAction extends Action

{

/*

StudentDAO sdao;

public void setSdao(StudentDAO sdao)

{

this.sdao=sdao;

}

*/

public ActionForward execute(ActionMapping am, ActionForm af, HttpServletRequest req, HttpServletResponse resp) throws Exception

{

DynaActionForm daf=(DynaActionForm)af;

System.out.println(daf.get("name").toString());

System.out.println(daf.get("email").toString());

System.out.println(daf.get("mobile").toString());

/*

Student s=new Student();

s.setName(...);

s.setEmail(...);

s.setMobile(...);

sdao.insert(s);

*/

return am.findForward("SUCCESS");

}

}

struts-config.xml

action-servlet.xml

Take web project

Add Struts capabilities

Add Spring capabilities

AOP (Aspect Oriented Programming)

- The importance of AOP is to seperate secondary / cross cutting concerns (middleware service implementations - TX, security, logging, session management, state persistence etc services) from primary / core concerns (business logic implementation).

- AOP recommends to write one Advice for each service implementation

-The types of Advices are

i) Method before Advice - sub class of MethodBeforeAdvice

ii) After Advice - sub class of AfterReturningAdvice

iii) Around Advice - sub class of MethodInterceptor (3rd party vendor)

iv) Throws Advice - sub class of ThrowsAdvice

- To weave target object (means business logic component) and interceptors (means sub classes of Advices) must be passed into ProxyFactoryBean class instance. PFB produces proxy object for business logic component (StudentController)

- Configure business logic component, Advice classes and ProxyFactoryBean in spring config file. Obtain PFB object ref into client and access proxy object of business logic component

- Do one example on applying AOP on StudentController bean

1) Open MyEclipse

2) Create new Java project

Name: spring_aop_5

3) Add Spring capabilities

Add Core Libraries

Add AOP Libraries

Add ORM/DAO Libraries

Add Misc Libraries

Uncheck spring config file

Click on Finish

4) Files/Classes required in this project are:

i) Student.java

ii) StudentDAO.java

iii) StudentDBDAO.java

iv) StudentHibDAO.java

v) StudentController.java

vi) MBA.java

vii) ARA.java

viii) AA.java

ix) TA.java

x) beans.xml

xi) Student.hbm.xml

xii) log4j.properties

xiii) StudentClient.java

5) Create log4j.properties

Right click on the project-> New-> File->

Name: log4j.properties

log4j.rootLogger=debug, A1

log4j.appender.A1=org.apache.log4j.ConsoleAppender

log4j.appender.A1.layout=org.apache.log4j.SimpleLayout

6) Create Advice class

-Right click on project-> New-> Class->

Name: MBA.java

public class MBA implements MethodBeforeAdvice

{

public void before(Method m, Object args[], Object target) throws Throwable

{

PropertyConfigurator. configure("log4j.properties");

Logger l=Logger.getLogger(MBA.class);

l.info("In MBA class");

l.info(m.getName());

l.info(args.length+"");

l.info(target.getClass().getName());

}

}

Name: ARA.java

public class ARA implements AfterReturningAdvice

{

public void afterReturning(Object returnValue, Method m, Object args[], Object target) throws Throwable

{

PropertyConfigurator.configure("log4j.properties");

Logger l=Logger.getLogger(ARA.class);

l.info(returnValue.getClass().getName());

l.info(returnValue);

}

}

Name: AA.java

public class AA implements MethodInterceptor

{

public Object invoke(MethodInvocation mi) throws Throwable

{

mi.proceed();

}

}

// TA.java

public class TA implements ThrowsAdvice

{

public void afterThrowing(Throwable t) throws Throwable

{

System.err.println(t.getClass().getName());

t.printStackTrace();

}

}

7) beans.xml

mba

aa

ara

ta

8) StudentClient.java

public class StudentClient

{

public static void main(String rags[]) throws Exception

{

BeanFactory f=new FileSystemXmlApplicationContext("beans.xml");

ProxyFactoryBean pfb=(ProxyFactoryBean)f.getBean("pfb");

Object o=pfb.getObject();

// proxy of StudentController object

StudentController sc=(StudentController)o;

Student s=new Student();

s.setSname("Rodrez");

s.setEmail("rodrez@mpd.com");

s.setMobile("232323333");

sc.addStudent(s);

System.out.println("Student added");

}

}

// SimplePointcut.java

public class SimplePointcut extends StaticMethodMatcherPointcut

{

public boolean matches(Method m, Class c)

{

if(m.getName().equals("addStudent") && c.getName().equals("StudentController"))

return true;

else

return false;

}

}

// StudentClient.java

ProxyFactoryBean pfb=new ProxyFactoryBean();

pfb.setTarget((StudentController)f.getBean("sc"));

pfb.addAdvisor(new DefaultPointcutAdvisor(new SimplePointcut(), new MBA()));

pfb.addAdvisor(new DefaultPointcutAdvisor(new SimplePointcut(), new ARA()));

pfb.addAdvisor(new DefaultPointcutAdvisor(new SimplePointcut(), new AA()));

pfb.addAdvisor(new DefaultPointcutAdvisor(new SimplePointcut(), new TA()));

StudentController sc=(StudentController)pfb.getObject();

// create student instance

sc.add(s);

Hibernate

Hibernate Framework

(Model Framework/ORM Framework)

ORM - Object Relation Mapping)

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

Features

1) Makes persistence (INSERT/UPDATE/DELETE) operations transparent (invisible) to developer

In traditional JDBC program developer used to

-obtain connection via --DriverManager.getConnection() method (or) via by connection pooling

--Determine to use Statement or PreparedStatement object

--SQL statement managements

--Consuming resultset

--ensuring Atomicity & Consistency

In Hibernate

--we must write one XML document named "hibernate-cfg.xml" that contains JDBC driver information

--Write one Java Bean class for each table whose properties are same as table columns and their types

--Optionally one XML document that maps each JavaBean to table and its properties, save the document as Student.hbm.xml file

--Input both cfg.xml and hbm.xml files to Hibernate classes. Hibernate classes will internally create conn, stmt etc objects for SQL operations

--If we instantiate JavaBean, assign all the class instance variables with values and invoke only one function on hibernate class called save(bean) as argument. Hibernate reads javabean values, prepares one dynamic SQL statement and inserts record into DB.

--Atomicity and consistency are managed by hibernate implicitly

--This way hibernate reduces the JDBC code to do SQL operations on DB

--That means in Hibernate what developer must do is map one Java class to table. Hibernate maps the java object to one entity / record in the DB

-Hibernate does object-entity relation management

-Not only hibernate does persistence operations, it caches all the objects stored via Hibernate and as and when the record is modified in the DB, hibernate updates the state of javabean also. It implicitly avoids inconsistent problems

1) Transparent persistence operations

2) Object level relationship instead of maintaining relationship @ DB level. This is to facilitate portable relationships across all the DBs

3) Instead of fetching records from the DB using SQL and operating on ResultSet, we can fetch objects directly from Hibernate using HQL

4) Caching

-Memory level caching

-Disk level caching

Installation procedure of Hibernate

1) Download Hibernate software from www.hibernate.org site

- 2.x version is complaint to JDk 1.3/1.4

- 3.x version is complaint to JDK 5.0 & above

2) Extract hibernate.zip file in local drive

D:\Hibernate2.1.6\hibernate-2.1

|-doc

|-api - index.html (classes help)

|-reference

|-en

|-html_single - index.html

|-pdf - hibernate_reference.pdf

|-etc - hibernate.cfg.xml, hibernate.properties

3) Instead of updating System classpath

Maintain one copy of "ENV.cmd" file in our working directory. Run the cmd file each time when we logon to our folder

E:\active\hibernate\first\

ENV.cmd

hibernate.cfg.xml

Student.java

Student.hbm.xml

StudentClient1.java

ENV.cmd

SET CLASSPATH=%CLASSPATH%;D:\Hibernate2.1.6\hibernate-2.1\hibernate2.jar

hibernate.cfg.xml

-when writing this XML document. Copy

-hibernate properties can be collected from \etc\hibernate.properties file

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

"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

sun.jdbc.odbc.JdbcOdbcDriver

jdbc:odbc:oracledsn

active

activenet

net.sf.hibernate.dialect.Oracle9Dialect

true

Student.java

import java.io.*;

public class Student implements Serializable

{

private int sid;

private String sname,email,mobile;

public Student(){}

public void setSid(int sid)

{this.sid=sid;}

public void setSname(String sname)

{this.sname=sname;}

public void setEmail(String email)

{this.email=email;}

public void setMobile(String mobile)

{this.mobile=mobile;}

public int getSid()

{return sid;}

public String getSname()

{return sname;}

public String getEmail()

{return email;}

public String getMobile()

{return mobile;}

public String toString()

{

return sid+" "+sname+" "+email+" "+mobile;

}

}

Student.hbm.xml

Copy PI & statements from D:\Hibernate2.1.6\hibernate-2.1\eg\org\hibernate\auction

Student.hbm.xml

"-//Hibernate/Hibernate Mapping DTD 2.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

// StudentClient1.java

import net.sf.hibernate.*;

import net.sf.hibernate.cfg.*;

public class StudentClient1

{

public static void main(String rags[]) throws Exception

{

/*

-Configuration class loads "hibernate.cfg.xml" file from a method named configure()

-This method parses cfg.xml and hbm.xml files and stores the information into one object called SessionFactory

*/

Configuration c=new Configuration();

c.configure("/hibernate.cfg.xml");

// to create SessionFactory object

SessionFactory sf=c.buildSessionFactory();

/*

-SessionFactory contains driver properties (driverClass, url, user & pass), with that we want to create one session object.

-Session object means indirectly it is a connection object

-Not only Session hides JDBC connection, it also hides Statement, PreparedStatement and ResultSet objects (hides JDBC code)

-This class contains save(Object), update(Object), delete(Object), Object get(Class c, Serializable s)

*/

Session s=sf.openSession();

/*

-begin new transaction means con.setAutoCommit(false)

-indirectly we can as below

*/

Transaction t=s.beginTransaction();

/* create one student bean instance, populate values into it */

Student sb=new Student();

sb.setSid(2);

sb.setSname("Sharuk khan");

sb.setEmail("sharu@boly.com");

sb.setMobile("9848012345");

/* bean instance saved into session object */

s.save(sb);

/* During flush method record inserts into DB */

s.flush();

/* make changes permenent in DB */

t.commit();

/* close session object means closing connection object */

s.close();

}

}

E:\active\hibernate\first> ENV

E:\active\hibernate\first> javac StudentClient1.java

ENV.cmd

SET HL=D:\Hibernate2.1.6\hibernate-2.1\lib

SET CLASSPATH=%CLASSPATH%;D:\Hibernate2.1.6\hibernate-2.1\hibernate2.jar;%HL%\dom4j-1.4.jar;%HL%\commons-logging-1.0.4.jar;%HL%\commons-collections-2.1.1.jar

/* This program retrieves bean instance from the hibernate, updates mobile and updates the same bean into session and DB */

// StudentClient2.java

import net.sf.hibernate.*;

import net.sf.hibernate.cfg.*;

public class StudentClient2

{

public static void main(String rags[]) throws Exception

{

Session s=(new Configuration()).configure("/hibernate.cfg.xml").buildSessionFactory().openSession();

Object o=s.get(Student.class, new Integer(2));

Student sb=(Student)o;

System.out.println(sb.toString());

sb.setEmail("sharu@bolywood.com");

s.update(sb);

s.flush();

}

}

Hibernate Example on MyEclipse IDE

1) Configuring DB

-open MyEclipse

-Initially J2EE perspective is opened

-We must change UI perspective to DB perspective

-Click on Switch Perspective icon situated in the right top corner of MyEclipse-> Choose MyEclipse Database Explorer

-Click on "New" icon

-Enter properties

--ProfileName: OIV

--Click on Configure database Driver

--Click on New button

--Driver Template: Oracle (Thin Driver)

--click on "Add Jars" button

--and select Oracle jar file

d:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar file

--Connection URL: jdbc:oracle:thin:@localhost:1521:XE

--click on OK button

--click on OK button

--URL: jdbc:oracle:thin:@localhost:1521:XE

--user: active

--pass: activenet

--click on "Next" and "Finish"

DB profile configuration is completed

2) Create new Java Project

Switch to MyEclipse J2EE perspective

File-> New-> Project-> Java Project

Project Name: hib_hql_2

Click on "Next" and "Finish"

3) Adding Hibernate capabilities

Right click on project "hib_hql_2"-> choose MyEclipse-> Add Hibernate Capabilities

Choose Hibernate 2 radio button

click on Next

click on Next

choose "Use JDBC driver"

choose DB profile: OIV

password: activenet

click on "Next"

uncheck "Create SessionFactory class" checkbox

click on Finish

Click on Add button under properties list box

choose property: show_sql

value: true

click on save button and exit from file

Copy Student.java and Student.hbm.xml files from our first example

4) Write a client program that uses HQL to retrieve beans from Hibernate

Right click on project-> New-> Java class

Name: StudentClient3

select "public static void main()" check box also

click on "Finish"

pulic static void main(String rags[]) throws Exception

{

Configuration c=new Configuration();

c.configure("/hibernate.cfg.xml");

SessionFactory sf=c.buildSessionFactory();

Session s=sf.openSession();

List l=s.find("FROM Student");

Iterator i=l.iterator();

while(i.hasNext())

{

Student sb=(Student)i.next();

System.out.println(sb);

}

}

save & exit from file

To compile and run Java file

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

Right click on StudentClient3.java file-> Choose "Run"-> "Java Application"

-Before running Java application, Open hibernate.cfg.xml file

-Click on "Add" button under Mappings list box

-Choose Student.hbm.xml file from our project tree structure

-Click on OK

Implement One-Many relationship in Hibernate using List

In this example, we must

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

1) Create two tables (Course, Batch)

2) Two JavaBeans

3) Configure JavaBeans in Student.hbm.xml file

4) Write a client program to insert course and all its corresponding batch instances into DB via Hibernate

1) Table creation

CREATE TABLE course (cid NUMBER,

cname VARCHAR2(100),

duration NUMBER,

fee NUMBER);

CREATE TABLE batch(bid NUMBER,

cid NUMBER,

bdate VARCHAR2(10),

faculty VARCHAR2(300),

idx NUMBER);

2) Bean generation

Right click on the project -> New-> Class

Name: Course

click on Finish

public class Course implements Serializable

{

private int cid, duration;

private String cname;

private double fee;

List batches;

// Right click on Java class-> select Source-> Generate Getters and Setters

public String toString()

{

return cid+" "+cname+" "+duration+" "+fee;

}

}

// Batch.java

public class Batch implements Serializable

{

private int bid, cid;

private String bdate, faculty;

// generate getter and setter methods

public String toString()

{return bid+" "+cid+" "+bdate+" "+faculty;}

}

3) Configure Student.hbm.xml file

4) Write a client program

public class CourseClient

{

public static void main(String rags[]) throws Exception

{

Configuration c=new Configuration();

c.configure("/hibernate.cfg.xml");

SessionFactory sf=c.buildSessionFactory();

Session s=sf.openSession();

Transaction t=s.beginTransaction();

// create batch instance

Batch b1=new Batch();

b1.setBid(1);

b1.setBdate("1-5-2008");

b1.setFaculty("Su...");

s.save(b1);

// create one more batch instance

Batch b2=new Batch();

b2.setBid(2);

b2.setBdate("15-5-2008");

b2.setFaculty("Mallik");

s.save(b2);

// create Course instance

Course cr=new Course();

cr.setCid(1);

cr.setCname("Core Java");

cr.setFee(0.0);

cr.setDuration(45);

List l=new ArrayList();

l.add(b1);

l.add(b2);

cr.setBatches(l);

s.save(cr);

s.flush();

t.commit();

s.close();

}

}

5) Write another client program that fetch Course and List of Batch details from DB

Session s=sf.openSession();

Query q=s.createQuery("FROM Course");

List l=q.list();

Iterator i=l.iterator();

while(i.hasNext())

{

Course cr=(Course)i.next();

System.out.println(cr);

// retrieve batch objects

List l1=cr.getBatches();

Iterator i1=l1.iterator();

while(i1.hasNext())

{

Batch b=(Batch)i1.next();

System.out.println(b);

}

}

PK generation strategy

1) hilo

-This PK generation algorithm uses one seperate table for each table

-For instance for "student" table, one "studentpk" table must be created with our own user defined column

CREATE TABLE studentpk (studid NUMBER);

-After generating PK table we must specify the table in hbm.xml file

hilo">

studentpk

studid

1

-Hibernate says that it takes one default tablename and columnname if hilo algorithm is mentioned without specifying table and column name

hilo"/>

-Hibernate takes default table name as "hibenate_unique_key" and column name as "next_hi"

-With this feature PK value is unique across the entire DB schema but not to a table

2) sequence

-This another PK generation technique we can use for oracle DB

-In this case one sequence must be created for each table

-For instance for "Student" table

CREATE SEQUENCE studentseq start with 1 increment by 1;

-In this technique .hbm.xml file must be updated as

studentseq

CREATE TABLE hibernate_unique_key (next_hi NUMBER);

INSERT INTO hibernate_unique_key VALUES (1);

COMMIT;

CLE SCR;

CREATE TABLE studentpk (studentsid NUMBER);

INSERT INTO studentpk VALUES (1);

COMMIT;

CLE SCR;

CREATE SEQUENCE studentseq start with 1 increment by 1;

To generate tables automatically

-In hibernate.cfg.xml file

true

create|create-drop|update

In our previous on-many relationship example (Course-Batch)

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

-If we want weak association between Course & Student

.hbm.xml

-----------

-For strong association between Course & Batch

Struts

Action classes

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

1) Action

2) DispatchAction

3) EventDispatchAction

4) LookupDispatchAction

5) MappingDispatchAction

6) DownloadAction

7) LocaleAction

8) ForwardAction

9) IncludeAction

10) SwitchAction

EventDispatchAction

-EventDispatchAction is a sub class of DispatchAction

-Developer must derive Action class from EventDispatchAction and must implement functions same as DispatchAction class

-But in DispatchAction the parameter attribute in struts-config.xml file contains request parameter name (like "method"), each form submitting to struts must submit request parameter name along with function want to be executed in DispatchAction class as request parameter value

-In EventDispatchAction, developer after implementing all the functions on Action class, the function names must be registered in parameter attribute with comma seperator. This is an indication that action class is registering all its functions as events in s-c.xml file. JSP which are requesting to the same action path must use request parameter name same as one of the event name registered in s-c.xml file. JSP those which doesn't satisfy this condition will get JSP compilation error

-Configuring EDA sub classes in s-c.xml

-During client request

If no event name is specified as request parameter the default event will be taken

-Otherwise

LookupDispatchAction

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

-Developer must sub class Action class from LookupDispatchAction class and must implement one function called getKeyMethodMap()

-The getKeyMethodMap() function returns Map object

-The Map object contains messagekey mapped to function name

-During client request the form must submit request parameter name as "function" (this name is config in s-c.xml file) and its value (request parameter value) must match with one of the message value exist in ApplicationResources.properties file

-The moment RequestProcessor receives client request, RP read req parameter value and checks for the message value in AR.properties file, the corresponding message key is retrieved

-RP instantiates Action class, invokes getKeyMethodMap() function, lookupfor the message key in map object, retrieves corresponding value from Map object and assumes that value as business logic function in Action class

public class UserAction extends LookupDispatchAction

{

protected Map getKeyMethodMap()

{

Map m=new HashMap();

m.add("button.add","insert");

m.add("button.update","update");

return m;

}

insert(), update() functions are as usual

}

ApplicationResources.properties

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

button.add=Add User

button.update=Update User

s-c.xml

-------

InsertUser.jsp

MappingDispatchAction

-The Action class must be sub classing from MappingDispatchAction with the function same as before

-The same Action class is mapped in s-c.xml file with different action paths and each such configuration contains parameter name that holds function want to be executed on Action class

UserInsert.jsp

UserUpdate.jsp

ForwardAction

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

-This Action is used to connect to java web components & web documents through Struts framework

-Functioning is same as RequestDispatcher.forward() operation in Servlets & tag of JSP

-When using this Action class developer need not have to derive any class from ForwardAction

-When client request action path, the path must be mapped to org.apache.struts.actions.ForwardAction class in struts-config.xml file and its parameter could be pointing to JSP, Servlet (old web components if any exist) and action path to another struts module within the same web application

IncludeAction

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

Same as ForwardAction except include() operation is used on JSP, Servlet and action paths of other modules

LocaleAction

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

-This action class is used to change the localization of user

-When request comes to action path of struts-config.xml file map the same to LocaleAction class

-This class implicitly reads two request parameters "language" and "country" and changes Locale object information @ session level

-Link from JSP document must as follows

Mexico

-In struts-config.xml file

Example on simple form validation in MyEclipse IDE 5.1/6.0

Open MyEclipse IDE

-Choose File-> New-> Project-> Web Project

Name: struts_form_2

Choose J2EE Level: 1.3

Finish

-Right click on web project folder, MyEclipse-> Add Struts capabilities

Struts config path: /WEB-INF/struts-config.xml

Struts spec: Struts 1.1

Action servlet name: action

URL pattern: *.do

Base package for java classes: beans

click on Finish

open beans/ApplicationResources.properties

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

prompt.field=Enter {0}

error.field.null={0} field should not be null

Create LoginForm.jsp in WebRoot

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

under project folder

WebRoot

LoginForm.jsp

Right click on WebRoot folder

choose New-> JSP

Name: LoginForm.jsp

Template: Standard JSP using Struts 1.1

LoginForm.jsp

<%@ page language="java" pageEncoding="ISO-8859-1"%>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-tiles" prefix="tiles" %>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-template" prefix="template" %>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-nested" prefix="nested" %>

Submit

LoginSuccess.html

Login Success

LoginFailed.html

Login Failed

Implement LoginActionFormm class

Right click on "src" folder

Choose-> New-> Class

package: beans

Name: LoginActionForm

Superclass: org.apache.struts.action.ActionForm

click on "Finish" button

// LoginActionForm.java

right click mouse right button anywhere on class, choose Source-> Generate Getters and Setters-> click on select All button

OK

public ActionErrors validate(ActionMapping arg0, HttpServletRequest arg1)

{

ActionErrors errors=new ActionErrors();

if(user==null || user.length()==0)

{

ActionError ae=new ActionError("error.field.null","Username");

errors.add("user", ae);

}

if(pass==null || pass.length()==0)

{

ActionError ae=new ActionError("error.field.null","Password");

errors.add("pass", ae);

}

return errors;

}

// LoginAction.java

struts-config.xml (WebRoot\WEB-INF folder)

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

sqlplus active/activenet

cle scr

create table login(

userid VARCHAR2(100),

pass VARCHAR2(100));

insert into login values('ABC', 'XYZ');

insert into login values('XYZ', 'ABC');

commit;

exit

-action-mapping updation in struts-config.xml

-tomcat configuration in MyEclipse IDE

-tomcat startup from IDE

-web application deployment

-table creation

-record insertion

-URL request from browser

tomcat configuration in MyEclipse IDE

-Click on Server icon located in the location bar of IDE

-choose "Configure Server"

-Expand "Application Servers"

--choose Tomcat 5

--Select "Enable" radio button

--Tomcat Home dir: D:\Tomcat 5.0

--click on "Apply" & "OK" buttons

tomcat server statup

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

-click on server icon again, choose Tomcat 5.0 from drop down menu, click on start button

deploying web application/ web project

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

-choose "strust_form_2" project from "Project Explorer"

-click on "Deploy icon" situated beside server icon in the toolbar

-Project: struts_form_2

-click on "Add" button

-Choose "Tomcat 5" from servers list

-click on "Finish" button

-click on "OK" button

create & insert records into login table

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

CREATE TABLE login(

userid VARCHAR2(100),

pass VARCHAR2(100));

INSERT INTO login VALUES('ABC', 'XYZ');

INSERT INTO login VALUES('XYZ', 'ABC');

commit;

exit from SQLPLUS editor

client request

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

http://localhost:65535/struts_form_2/LoginForm.jsp