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.
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:
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.
-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
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
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.
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) 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
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 mobileand 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
-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