Thursday, July 10, 2008

Hibernate Validator

Hibernate Validator

Project Lead:

Emmanuel Bernard

Latest release:

3.0.0 GA (Changelog) (Road Map)

Release date:

20.03.2007

Requirements:

Hibernate Core 3.2, JDK 5.0

Following the DRY (Don't Repeat Yourself) principle, Hibernate Validator let's you express your domain constraints once (and only once) and ensure their compliance at various level of your system automatically.

Annotations are a very convenient and elegant way to specify invariant constraints on the domain model implementation, the persistent classes. Hibernate Validator comes bundled with a set of common validations (@NotNull, @Email, @Max, and so on), and you can build you own validation rules very easily.

This is an example of an annotated persistent class:

public class Address {
 
    @NotNull private String line1;
    private String line2;
    private String zip;
    private String state;
    
    @Length(max = 20)
    @NotNull
    private String country;
 
    @Range(min = -2, max = 50, message = "Floor out of range")
    public int floor;
 
        ...
}

Hibernate Validator integrates with Hibernate by applying the constraints on the database schema (DDL generation) and by checking entity validity before Hibernate inserts or updates instances. You can use Hibernate Validator with any Java Persistence provider, not only Hibernate, although you will not be able to use automatic DDL alteration for constraint generation outside of Hibernate EntityManager.

Hibernate Validator constraint checking can be triggered programmatically, for example by the business layer. JBoss Seam makes use of this capability and integrates it with JSF, providing end to end validation from the presentation level down to the database constraints with a unique definition and declaration of integrity rules. Hibernate Validator is fully internationalized.

The project lead of Hibernate Validator is an expert group member of JSR 303: Bean Validation.

32.What are the Collection types in Hibernate ?

* Bag

* Set

* List

* Array

* Map

31.What is the advantage of Hibernate over jdbc?

Hibernate Vs. JDBC :-

JDBC

Hibernate

With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema.

Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.

With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code.

Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.

JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task.

Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.

Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table.

Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.

With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.

Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.

With JDBC, caching is maintained by hand-coding.

Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.

In JDBC there is no check that always every user has updated data. This check has to be added by the developer.

Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.

32.What are the Collection types in Hibernate ?

* Bag

* Set

* List

* Array

* Map


33.What are the ways to express joins in HQL?

HQL provides four ways of expressing (inner and outer) joins:-

* An implicit association join

* An ordinary join in the FROM clause

* A fetch join in the FROM clause.

* A theta-style join in the WHERE clause.


34.Define cascade and inverse option in one-many mapping?

cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

37.How can a whole class be mapped as immutable?


Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.

44.What are the differences between EJB 3.0 & Hibernate

Hibernate Vs EJB 3.0 :-

Hibernate

EJB 3.0

Session–Cache or collection of loaded objects relating to a single unit of work

Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit

XDoclet Annotations used to support Attribute Oriented Programming

Java 5.0 Annotations used to support Attribute Oriented Programming

Defines HQL for expressing queries to the database

Defines EJB QL for expressing queries

Supports Entity Relationships through mapping files and annotations in JavaDoc

Support Entity Relationships through Java 5.0 annotations

Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API

Provides and Entity Manager Interface for managing CRUD operations for an Entity

Provides callback support through lifecycle, interceptor, and validatable interfaces

Provides callback support through Entity Listener and Callback methods

Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships

Entity Relationships are bidirectional or unidirectional


45.What are the types of inheritance models in Hibernate?

There are three types of inheritance models in Hibernate:

* Table per class hierarchy

* Table per subclass

* Table per concrete class

Enum-- jcsp examples

Question 14

Given:

10. class Nav{

11. public enum Direction { NORTH, SOUTH, EAST, WEST }

12. }

13. public class Sprite{

14. // insert code here

15. }

Which code, inserted at line 14, allows the Sprite class to compile?

A. Direction d = NORTH;

B. Nav.Direction d = NORTH;

C. Direction d = Direction.NORTH;

D. Nav.Direction d = Nav.Direction.NORTH;

Answer: D

*********

Question 17

Given:

1. package sun.scjp;

2. public enum Color { RED, GREEN, BLUE }

1. package sun.beta;

2. // insert code here

3. public class Beta {

4. Color g = GREEN;

5. public static void main( String[] argv)

6. { System.out.println( GREEN); }

7. }

The class Beta and the enum Color are in different packages.

Which two code fragments, inserted individually at line 2 of the Beta

declaration, will allow this code to compile? (Choose two.)

A. import sun.scjp.Color.*;

B. import static sun.scjp.Color.*;

C. import sun.scjp.Color; import static sun.scjp.Color.*;

D. import sun.scjp.*; import static sun.scjp.Color.*;

E. import sun.scjp.Color; import static sun.scjp.Color.GREEN;

Answer: CE

***********

Question 32

Given:

11. public class Ball {

12. public enum Color { RED, GREEN, BLUE };

13. public void foo() {

14. // insert code here

15. { System.out.println(c); }

16. }

17. }

Which code inserted at line 14 causes the foo method to print RED,

GREEN, and BLUE?

A. for( Color c : Color.values())

B. for( Color c = RED; c <= BLUE; c++)

C. for( Color c; c.hasNext() ; c.next())

D. for( Color c = Color[0]; c <= Color[2]; c++)

E. for( Color c = Color.RED; c <= Color.BLUE; c++)

Answer: A

***********

Question 33

Given:

10. public class Fabric

11. public enum Color {

12. RED(0xff0000), GREEN(0x00ff00), BLUE(0x0000ff);

13. private final int rgb;

14. Color( int rgb) { this.rgb = rgb; }

15. public int getRGB() { return rgb; }

16. };

17. public static void main( String[] argv) {

18. // insert code here

19. }

20. }

Which two code fragments, inserted independently at line 18, allow the

Fabric class to compile? (Choose two.)

A. Color skyColor = BLUE;

B. Color treeColor = Color.GREEN;

C. Color purple = new Color( 0xff00ff);

D. if( RED.getRGB() < BLUE.getRGB() ) {}

E. Color purple = Color.BLUE + Color.RED;

F. if( Color.RED.ordinal() < Color.BLUE.ordinal() ) {}

Answer: BF

**************

Question 34

Given:

11. public enum Title {

12. MR(”Mr.”), MRS(”Mrs.”), MS(”Ms.”);

13. private final String title;

14. private Title(String t) { title = t; }

15. public String format(String last, String first) {

16. return title + “ “ + first + “ “ + last;

17. }

18. }

19. public static void main(String[] args) {

20. System.out.println(Title.MR.format(”Doe”, “John”));

21. }

What is the result?

A. Mr. John Doe

B. An exception is thrown at runtime.

C. Compilation fails because of an error in line 12.

D. Compilation fails because of an error in line 15.

E. Compilation fails because of an error in line 20.

Answer: A

***********

Question 52

Given:

11. public class Test {

12. public enum Dogs {collie, harrier, shepherd};

13. public static void main(String [] args) {

14. Dogs myDog = Dogs.shepherd;

15. switch (myDog) {

16. case collie:

17. System.out.print(”collie “);

18. case default:

19. System.out.print(”retriever “);

20. case harrier:

21. System.out.print(”harrier “);

22. }

23. }

24. }

‘What is the result?

A. harrier

B. shepherd

C. retriever

D. Compilation fails.

E. retriever harrier

F. An exception is thrown at runtime.

Answer: D

***********

Question 53

Given:

12. public class Test {

13. public enum Dogs {collie, harrier};

14. public static void main(String [] args) {

15. Dogs myDog = Dogs.collie;

16. switch (myDog) {

17. case collie:

18. System.out.print(”collie “);

19. case harrier:

20. System.out.print(”harrier “);

21. }

22. }

23. }

What is the result?

A. collie

B. harrier

C. Compilation fails.

D. collie harrier

E. An exception is thrown at runtime.

Answer: D

***********

Question 20

Given:

1. interface TestA { String toString(); }

2. public class Test {

3. public static void main(String[] args) {

4. System.out.println(new TestA() {

5. public String toString() { return “test”; }

6. });

7. }

8. }

What is the result?

A. test

B. null

C. An exception is thrown at runtime.

D. Compilation fails because of an error in line 1.

E. Compilation fails because of an error in line 4.

F. Compilation fails because of an error in line 5.

Answer: A

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