Java Notes

77
ANT Installing Ant Regardless of platform, downloading Ant is the first step to installing the software. The files can be downloaded to a temporary directory and then uncompressed to any desired directory. After the download step, the process differs depending on whether you've downloaded the binary distribution or the source distribution. Ant does not provide an installation program; it runs from wherever you choose to copy the files and directories. Lists the directories that ultimately get created under your main Ant directory. Directories provided with Ant bin - Batch files, Perl scripts, and shell scripts for running Ant. docs - Ant documentation. lib - Libraries required by Ant to run. src - Source code for Ant. Provided only in the source distribution. Binary Installation The term "binary" just means that everything is compiled and packaged into JAR files for easy execution — you don't need to compile Ant from source. Steps to install Installation of the binary distribution: 1. Unzip (or untar) the distribution to the desired directory. 2. Set the ANT_HOME environment variable to point to to the ant installation directory. 3. Set the JAVA_HOME environment variable to point to the JDK location. 4. Add ANT_HOME/bin to your system's PATH environment variable. The ant script uses the ANT_HOME and JAVA_HOME environment variables to configure the CLASSPATH used by the JVM running Ant. If these variables are not set, the startup script attempts to infer the correct values, subject to operating system limitations. Source Installation Installing the Ant source distribution requires a little more work than installing the binary distribution. As expected, downloading and uncompressing the distribution is the first step. You generally want to place the source files in a directory separate from any existing Ant installations. Next, ensure that JAVA_HOME points to the JDK distribution. As with the binary installation, you should also set ANT_HOME and update your PATH. type the following command from the source distribution directory:

Transcript of Java Notes

Page 1: Java Notes

ANT

Installing Ant  

Regardless of platform, downloading Ant is the first step to installing the software. The files can be downloaded to a temporary directory and then uncompressed to any desired directory. After the download step, the process differs depending on whether you've downloaded the binary distribution or the source distribution.Ant does not provide an installation program; it runs from wherever you choose to copy the files and directories. Lists the directories that ultimately get created under your main Ant directory.

Directories provided with Antbin - Batch files, Perl scripts, and shell scripts for running Ant.docs - Ant documentation.lib - Libraries required by Ant to run.src - Source code for Ant. Provided only in the source distribution. 

Binary InstallationThe term "binary" just means that everything is compiled and packaged into JAR files for easy execution — you don't need to compile Ant from source.Steps to install Installation of the binary distribution: 1. Unzip (or untar) the distribution to the desired directory.2. Set the ANT_HOME environment variable to point to to the ant installation directory.3. Set the JAVA_HOME environment variable to point to the JDK location.4. Add ANT_HOME/bin to your system's PATH environment variable.

The ant script uses the ANT_HOME and JAVA_HOME environment variables to configure the CLASSPATH used by the JVM running Ant. If these variables are not set, the startup script attempts to infer the correct values, subject to operating system limitations.

Source InstallationInstalling the Ant source distribution requires a little more work than installing the binary distribution. As expected, downloading and uncompressing the distribution is the first step.You generally want to place the source files in a directory separate from any existing Ant installations. Next, ensure that JAVA_HOME points to the JDK distribution. As with the binary installation, you should also set ANT_HOME and update your PATH.type the following command from the source distribution directory:

build -Ddist.dir=destination_directory dist (Windows)build.sh -Ddist.dir=destination_directory dist (Unix)

The build script creates a complete binary distribution of Ant in the specified destination directory. When omitted, dist.dir defaults to build.

Ant Basics  

Page 2: Java Notes

Each 'Project' has a Build File, Default build file name is 'build.xml', Can Specify any name with '-buildfile' command line option, Ant's buildfiles are written in XML.

The first or root element of any buildfile is always the <project> tag. No buildfile can be without one nor can it have more than one.

<project name="MyProject" default="all" basedir=".">...</project>

The <project> tag has three attributes: name, default, and basedir.

The name attribute gives the project a name. The default attribute refers to a target name within the buildfile. If you run Ant

without specifying a target on the command line, Ant executes the default target. If the default target doesn't exist, Ant returns an error.

The basedir attribute defines the root directory of a project. Typically, it is ".", the directory in which the buildfile resides, regardless of the directory you're in when you run Ant. However, basedir can also define different points of reference.

Each buildfile contains one project and at least one (default) target. Examples are: 'compile', 'test', 'install', 'clean', etc.<target name="dosomething">  <task1 param1="value1" param2="value2">

  <task2 param3="value3" >

  ...</target>

The <target> tag has three attributes: name, depends, if, unless, descriptiondefault, and basedir. 

The name attribute gives the target a name. The depends attribute are a comma-separated list of names of targets on which this

target depends. The if attribute the name of the property that must be set in order for this target to

execute. The unless attribute the name of the property that must not be set in order for this

target to execute. The description attribute a short description of this target's function.

Targets must have a name and may have several additional attributes that determine when and if the target actually gets executed. The target is made up of one or more Tasks like invoke a command or another program. Targets can have Dependencies, examples: 'install' depends on 'compile', Targets can handle cascading dependencies, each Dependency is handled only once, dependency executed only if required.

It should be noted, however, that Ant's depends attribute only specifies the order in which targets should be executed - it does not affect whether the target that specifies the

Page 3: Java Notes

dependency(s) gets executed if the dependent target(s) did not (need to) run. 

Ant tries to execute the targets in the depends attribute in the order they appear (from left to right). Keep in mind that it is possible that a target can get executed earlier when an earlier target depends on it.A target gets executed only once, even when more than one target depends on it .

A <task> is a piece of code that can be executed.A task can have multiple attributes (or arguments, if you prefer). The value of an attribute might contain references to a property. These references will be resolved before the task is executed. Tasks have a common structure:<name attribute1="value1" attribute2="value2" ... /> where name is the name of the task, attributeN is the attribute name, and valueN is the value for this attribute.

Each task element of the buildfile can have an id attribute and can later be referred to by the value supplied to this. The value has to be unique. Each Task is bound to a Java class file that Ant executes, passing to it any arguments or sub-elements defined with that task. The Ant tool is extensible and it allows you to create your own tasks 

Typical build.xml Tasksinit, sets properties, prepare, creates directories, build, builds the system, package, creates jar file, install, installs an application to Tomcat or other engine, deploy, deploy a WAR engine, reload, update previously installed application engine, redeploy.

Properties 

A project can have a set of properties. These might be set in the buildfile by the property task, or might be set outside Ant. A property has a name and a value; the name is case-sensitive. Properties may be used in the value of task attributes. This is done by placing the property name between "${" and "}" in the attribute value. For example, if there is a "builddir" property with the value "build", then this could be used in an attribute like this: ${builddir}/classes. This is resolved at run-time as build/classes.

Built-in PropertiesAnt provides access to all system properties as if they had been defined using a <property> task. For example, ${os.name} expands to the name of the operating system. For a list of system properties see the Javadoc of System.getProperties. In addition, Ant has some built-in properties:

basedir the absolute path of the project's basedir (as set with the basedir attribute of <project>).ant.file the absolute path of the buildfile.ant.version the version of Antant.project.name the name of the project that is currently executing; it is set in the name attribute of <project>.ant.java.version the JVM version Ant detected; currently it can holdthe values "1.1", "1.2", "1.3" and "1.4".

Using Ant  

Page 4: Java Notes

Ant is a Java based build tool, similar to make, but with better support for the cross platform issues involved with developing Java applications. Ant is the build tool of choice for all Java projects at Apache and many other Open Source Java projects. Ant can be configured to compile your java source code files, build your deployment JAR and WAR files, unit-test code and create projects javadoc documentation.

Ant 1.6.0 adds a lot of new features, most prominently support for XML namespaces as well as a new concept of Ant libraries that makes use of namespaces to avoid name clashes of custom tasks. 

Advantages of Ant

Build IN Java, USING Java, and FOR Java Supports Java Tools (javac, javadoc, etc.) XML Build File is Easier to Build, Read, and Maintain than MAKE file Easier to Extend Supports Cross Platform Java Development Ant is much faster than using MAKE ? Each command is a new process Ant runs within the JVM Each command is executed from within JVM Tools like javac are new threads – not new process Compiling large number of java source files is MUCH,MUCH faster with Ant Ant's Debug Options are very helpful XML much easier to read than MAKEFILE User does not need to know all command line interface options to tools that can be

called programmatically Even OS-Specific commands can be setup in 'TaskDefs' and/or included from other

sources

Running Ant  

Command LineIf you've installed Ant as described in the Installing Ant section, running Ant from the command-line is simple: just type ant.

When no arguments are specified, Ant looks for a build.xml file in the current directory and, if found, uses that file as the build file and runs the target specified in the default attribute of the <project> tag. To make Ant use a build file other than build.xml, use the command-line option -buildfile file, where file is the name of the build file you want to use

If you use the -find [file] option, Ant will search for a build file first in the current directory, then in the parent directory, and so on, until either a build file is found or the root of the filesystem has been reached. By default, it will look for a build file called build.xml. To have it search for a build file other than build.xml, specify a file argument. 

Note: If you include any other flags or arguments on the command line after the -find flag, you must include the file argument for the -find flag, even if the name of the build file you want to find is build.xml. 

You can also set properties on the command line. This can be done with the -Dproperty=value option, where property is the name of the property, and value is the value for that property. If you specify a property that is also set in the build file (see the property

Page 5: Java Notes

task), the value specified on the command line will override the value specified in the build file. Defining properties on the command line can also be used to pass in the value of environment variables - just pass -DMYVAR=%MYVAR% (Windows) or -DMYVAR=$MYVAR (Unix) to Ant. You can then access these variables inside your build file as ${MYVAR}. You can also access environment variables using the property task's environment attribute.

Options that affect the amount of logging output by Ant are:-quiet, which instructs Ant to print less information to the console;-verbose, which causes Ant to print additional information to the console;-debug, which causes Ant to print considerably more additional information. It is also possible to specify one or more targets that should be executed. When omitted, the target that is specified in the default attribute of the project tag is used.The -projecthelp option prints out a list of the build file's targets. Targets that include a description attribute are listed as "Main targets", those without a description are listed as "Subtargets", then the "Default" target is listed.

Command-line Options Summaryant [options] [target [target2 [target3] ...]]

Options:

-help, -h print this message-projecthelp, -p print project help information-version print the version information and exit-diagnostics print information that might be helpful to diagnose or report problems.-quiet, -q be extra quiet-verbose, -v be extra verbose-debug, -d print debugging information-emacs, -e produce logging information without adornments-lib <path> specifies a path to search for jars and classes-logfile <file> use given file for log-l <file> use given file for log-logger <classname> the class which is to perform logging-listener <classname> add an instance of class as a project listener-noinput do not allow interactive input-buildfile <file> use given buildfile-file <file> use given buildfile-f <file> use given buildfile-D<property>=<value> use value for given property-keep-going, -k execute all targets that do not depend on failed target(s)-propertyfile <name> load all properties from file with -D properties taking precedence-inputhandler <class> the class which will handle input requests-find <file> (s)earch for buildfile towards the root of-s <file> the filesystem and use it

Ant tasks  

The following tables provide a short description of each task.

Archive Tasks (Jar, Ear, Tar, War, GZip, Zip etc.) Audit/Coverage Tasks (JDepend, JPorbe, MMetrics, etc. ) Compile Tasks (javac, jspc, rmic etc.) Deployment Tasks (ServerDeploy) Documentation Tasks (Javadoc, Stylebook) EJB Tasks Execution Tasks (Ant, Antcall, Exec, Java, Sleep etc.) File Tasks (Attrib, Copy, Copydir, delete, Mkdir etc.) Java2 Extensions Tasks (Jarlib-available, Jarlib-display etc.) Logging Tasks (Record) Mail Tasks (Mail, MimeMail) Miscellaneous Tasks (Echo, GenKey, Script, Sql etc.) .NET Tasks Pre-process Tasks (ANTLR, AntStructure, Import, Xslt/Style etc.) Property Tasks (Available, Basename, BuildNumber, LoadFile etc.) Remote Tasks (FTP, Telnet etc. ) SCM Tasks (Cvs, CvsChangeLog, CVSPass etc.)

Page 6: Java Notes

Testing Tasks (Junit, JunitReport, Test) Visual Age for Java Tasks

Ant command line arguments

Several tasks take arguments that will be passed to another process on the command line. To make it easier to specify arguments that contain space characters, nested arg elements can be used.

value - a single command-line argument; can contain space characters.file - The name of a file as a single command-line argument; will be replaced with the absolute filename of the file.path - A string that will be treated as a path-like string as a single command-line argument; you can use ; or : as path separators and Ant will convert it to the platform's local conventions.pathref - Reference to a path defined elsewhere. Ant will convert it to the platform's local conventions.line - a space-delimited list of command-line arguments.

It is highly recommended to avoid the line version when possible. Ant will try to split the command line in a way similar to what a (Unix) shell would do, but may create something that is very different from what you expect under some circumstances. 

Examples<arg value="-l -a"/>is a single command-line argument containing a space character.<arg line="-l -a"/>represents two separate command-line arguments.<arg path="/dir;/dir2:\dir3"/>is a single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems. 

Command-line Options Summaryant [options] [target [target2 [target3] ...]] 

Options:

-help, -h Displays help information describing the Ant command and its options-projecthelp, -p Print project help information-version Print the version information and exit-diagnostics Print information that might be helpful to diagnose or report problems.-quiet, -q Suppresses most messages not originated by an echo task in the buildfile-verbose, -v Displays detailed messages for every operation during a build.-debug, -d Print debugging information-emacs, -e Produce logging information without adornments-lib <path> Specifies a path to search for jars and classes-logfile <file> Use given file for log-l <file> Use given file for log-logger <classname> Specifies a class to handle Ant logging.-listener <classname> Add an instance of class as a project listener-noinput Do not allow interactive input-buildfile <file> Use given buildfile-file <file> Use given buildfile-f <file> Use given buildfile-D<property>=<value> Defines a property name-value pair on the command line.-keep-going, -k execute all targets that do not depend on failed target(s)-propertyfile <name> load all properties from file with -D properties taking precedence-inputhandler <class> the class which will handle input requests-find <file> Search for buildfile towards the root of the filesystem and use it

STRUTS

MVC

The MVC (Model-View-Controller) architecture the client request is first intercepted by a servlet referred as controller servlet. this servlet handles the initial processing of the request and determines which JSP page to display next. Here the controller servlet is the single point of entry, there is a clear sepration of business logic, presentation output and request

Page 7: Java Notes

processing. MCV architecture is a way of decomposing an application into three parts:

The model maintains the state and data that the application represents.The view allows the display of information about the model to the user.The controller allows the user to manipulate the application. the model, the view and the controller.

MVC was originally applied in the graphical user interaction model of input, processing and output.

In Struts, the view is handled by JSPs and presentation components, the model is represented by Java Beans and the controller uses Servlets to perform its action. 

Model A model represents an application’s data and contains the logic for accessing and manipulating that data. Any data that is part of the persistent state of the application should reside in the model objects. The business objects update the application state. ActionForm bean represents the Model state at a session or request level, and not at a persistent level. Model services are accessed by the controller for either querying or effecting a change in the model state. The model notifies the view when a state change occurs in the model.The JSP file reads information from the ActionForm bean using JSP tags. 

ViewThe view is responsible for rendering the state of the model. The presentation semantics are encapsulated within the view, therefore model data can be adapted for several different kinds of clients.The view modifies itself when a change in the model is communicated to the view. A view forwards user input to the controller.The view is simply a JSP or HTML file. There is no flow logic, no business logic, and no model information -- just tags. Tags are one of the things that make Struts unique compared to other frameworks like Velocity.

ControllerThe controller is responsible for intercepting and translating user input into actions tobe performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations.The Controller receives the request from the browser, and makes the decision where to send the request. With Struts, the Controller is a command design pattern implemented as a servlet. The struts-config.xml file configures the Controller.

Downloading Struts

Struts can be found as a subproject of the Jakarta project (http://jakarta.apache.org). 

For Struts documentation, install notes, and downloads, see the Struts Home page.

Installing Struts 

In order to do any Java development you need the Java Developer Kit. You can find JDK1.4 at http://java.sun.com.

Just execute the installation executable and follow the instructions.

You will need to setup the PATH and the JAVA HOME variables; 

Page 8: Java Notes

Struts can also be found as a subproject of the Jakarta project (http://jakarta.apache.org). There is no Struts installation for the moment, just uncompress it in a convenient directory.

Copy the following JAR files, extracted from the Jakarta Struts archive, to the/WEB-INF/lib directory:struts.jar commons-beanutils.jar commons-collections.jar commons-digester.jar commons-logging.jar commons-validator.jar 

Copy the tld files you want to use in the /WEB-INF directory:struts-html.tldstruts-bean.tld struts-logic.tldstruts-nested.tldstruts-template.tld

If you want to use tiles add the struts-tiles.tld also in the /WEB-INF directory.

Add struts-config.xml file in the /WEB-INF directory

Fot configuring the struts for you application refer to Configuring Struts.

For Struts documentation, install notes, and downloads, see the Struts Home page.

Configuring Struts 

Struts framework use two related type of configuration file, which nust be configured properly before and application will work correctly. Both configration files are XML based. The first one is the web application deployment descriptor web.xml and the second one the Struts configuration file, it is comonly named struts-config.xml.

Configuring web.xml

There are few Struts-specific configuration options that you must configure within this file when using the struts framework.

Modify the web.xml file in /WEB-INF directory by adding the .tld file you want to use like if you are using struts-html.tld then

<taglib>

 <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri><taglib-location>/WEB-INF/struts-html.tld</taglib-location>

</taglib>

Configure the ActionServlet that will receive all the incoming request for the appliation. The two steps involved in configuring the Struts controller servlet in the web.xml are, first to use the servlet element to configure the servlet instance that can be latter mapped in the servlet mapping element.

Page 9: Java Notes

Using servlet element to configure the servlet class in web.xml

<web-app>  <sertvlet>      <servlet-name>some name</servlet-name>

      <servlet-class>the class name</servlet-class>

    </sertvlet></web-app>       

Configure servlet mapping

<web-app>  <sertvlet>      <servlet-name>some name</servlet-name>

      <servlet-class>the class name</servlet-class>

    </sertvlet>

    <sertvlet-mapping>      <servlet-name>some name</servlet-name>      <url-pattern>*.do </url-pattern>

    </sertvlet-mapping></web-app>       

Struts 1.0 and 1.1

The new features added to Struts 1.1 are 

1. RequestProcessor class2. Method perform() replaced by execute() in Struts base Action Class3.4.5.6.7.8.910.11.12.13. 

Changes to web.xml and struts-config.xmlDeclarative exception handlingDynamic ActionFormsPlug-insMultiple Application ModulesNested TagsThe Struts ValidatorChange to the ORO packageChange to Commons loggingRemoval of Admin actionsDeprecation of the GenericDataSource

   

Struts Controller

The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations. The Controller receives the request from the browser, invoke a business operation and coordinating the view to return to the client.

The controller is implemented by a java servlet, this servlet is centralized point of control for

Page 10: Java Notes

the web application. In struts framework the controller responsibilities are implemented by several different components like

The ActionServlet Class The RequestProcessor ClassThe Action Class

The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your application.

The controller is implemented by the ActionServlet class. All incoming requests are mapped to the central controller in the deployment descriptor as follows.

<servlet>  <servlet-name>action</servlet-name>  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class></servlet>

All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows.

<servlet-mapping>  <servlet-name>action</servlet-name>  <url-pattern>*.do</url-pattern><url-pattern>*.do</url-pattern>

A request URI that matches this pattern will have the following form.http://www.my_site_name.com/mycontext/actionName.do

The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends with /* as shown below.

<servlet-mapping>  <servlet-name>action</servlet-name>  <url-pattern>/do/*</url-pattern><url-pattern>*.do</url-pattern>

A request URI that matches this pattern will have the following form.http://www.my_site_name.com/mycontext/do/action_Name

The class org.apache.struts.action.requestProcessor process the request from the controller. You can sublass the RequestProcessor with your own version and modify how the request is processed.

Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation associated with the requested action. In the Struts framework this helper class is descended oforg.apache.struts.action.Action class. It acts as a bridge between a client-side user action and business operation. The Action class decouples the client request from the business model. This decoupling allows for more than one-to-one mapping between the user request and an action. The Action class also can perform other functions such as

Page 11: Java Notes

authorization, logging before invoking business operation. the Struts Action class contains

several methods, but most important method is the execute() method.

public ActionForward execute(ActionMapping mapping,

 ActionForm form, HttpServletRequest request, HttpServletResponse response)

throws Exception;  

The execute() method is called by the controller when a request is received from a client. The controller creates an instance of the Action class if one doesn’t already exist. The strut framework will create only a single instance of each Action class in your application. 

Action are mapped in the struts configuration file and this configuration is loaded into memory at startup and made available to the framework at runtime. Each Action element is represented in memory by an instance of the org.apache.struts.action.ActionMapping class . The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request.

<action>  path= "/somerequest"  type="com.somepackage.someAction"  scope="request"  name="someForm"  validate="true"  input="somejsp.jsp"  <forward name="Success" path="/action/xys" redirect="true"/>  <forward name="Failure" path="/somejsp.jsp" redirect="true"/></action>

Once this is done the controller should determine which view to return to the client. The execute method signature in Action class has a return type org.apache.struts.action.ActionForward class. The ActionForward class represents a destination to which the controller may send control once an action has completed. Instead of specifying an actual JSP page in the code, you can declaratively associate as action forward through out the application. The action forward are specified in the configuration file.

<action>  path= "/somerequest"  type="com.somepackage.someAction"  scope="request"  name="someForm"  validate="true"  input="somejsp.jsp"  <forward name="Success" path="/action/xys" redirect="true"/>  <forward name="Failure" path="/somejsp.jsp" redirect="true"/></action>

The action forward mappings also can be specified in a global section, independent of any specific action mapping.

<global-forwards>  <forward name="Success" path="/action/somejsp.jsp" />

Page 12: Java Notes

  <forward name="Failure" path="/someotherjsp.jsp" /></global-forwards>

Struts Model

A model represents an application’s data and contains the logic for accessing and manipulating that data. Any data that is part of the persistent state of the application should reside in the model objects. The business objects update the application state. ActionForm bean represents the Model state at a session or request level, and not at a persistent level. Model services are accessed by the controller for either querying or effecting a change in the model state. The model notifies the view when a state change occurs in the model.The JSP file reads information from the ActionForm bean using JSP tags.

The Struts frame work doen't offer much in the way pf building model components. The Enterprise JavaBeans (EJB), Java Data Objects(JDO) and JavaBeans can be use as a model. Struts frame work doesn't limit you to one particular model implementation.

Struts View

The view is responsible for rendering the state of the model. The presentation semantics are encapsulated within the view, therefore model data can be adapted for several different kinds of clients.The view modifies itself when a change in the model is communicated to the view. A view forwards user input to the controller.The view is simply a JSP or HTML file. There is no flow logic, no business logic, and no model information -- just tags. Tags are one of the things that make Struts unique compared to other frameworks like Velocity.

The view components typically employed in a struts application are HTMLData Transfer ObjectsStruts ActionFormsJavaServer pagesCustom tagsJava resource bundles

Struts ActionFormStruts ActionForm objects are used to pass client input data back and forth between the user and the business layer. The framework automatically collects the input from the request and passes this data to an Action using a form bean, which is then passed to the business layer.

Struts Tag Library

The Struts framework provides a fairly rich set of framework components. It also includes a set of tag libraries that are designed to interact intimately with the rest o the framework. The customg tags provided by Struts framework are grouped into four distinct libraries1. HTML2. Bean3. Logic4. Template

And a special library called Nested tag library.

Custom tags with in Struts HTML tag library

Page 13: Java Notes

base - renders an HTML base elementbutton - renders a button input fielscancel - renders a cancel buttoncheckbox - renders a checkbox input fielderrors - conditionnaly renders a set of accumulated error messagesfile - renders a file select input fieldform - defines an HTML form elementframe - renders an HTML frame elementhidden - renders a hidden fieldhtml - renders an HTMl html elementimage - renders an input tag of type "image"img - renders an HTMl img tagjavascript - renderts JavaScript validation rules loaded by ValidationPluginlink - renders an HTML anchoror hyperlinkmessages - Conditionally displays a set of accumulated messagesmultibox -renders multiple checkbox input fieldsoption - renders a select optionoptions - renders a collection of select optionsoptions Collection - render a collection of select optionspassword -renders apassword input field

radio -renders a radio button input field

reset -renders a rest button input field

rewrite - renders a URI

select -renders a select element

submit -renders a submi button

text -renders an input field of type "text"

textarea -renders an textarea input field

Struts Example

Struts is modeled after the MVC design pattern, you can follow a standard development process for all of your Struts Web applications. 

Identificaty of the application Views, the Controller objects that will service those Views, and the Model components being operated on.

1. Define and create all of the Views, in relation to their purpose, that will represent the user interface of our application. Add all ActionForms used by the created Views to the struts-config.xml file.2. Create the components of the application’s Controller. 3. Define the relationships that exist between the Views and the Controllers (struts-config.xml). 4. Make the appropriate modifications to the web.xml file, describe the Struts components to the Web application.

Lets Start with step one. we will create the view file named index.jsp index.jsp

<%@ page language="java" %><%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html><head><title>Sample Struts Application</title></head><body>

  <html:form action="Name" name="nameForm" type="example.NameForm">

Page 14: Java Notes

    <table width="80%" border="0">

      <tr>

        <td>Name:</td>

        <td><html:text property="name" /></td>

      </tr>

      <tr>

        <td><html:submit /></td>

      </tr>

    </table>

  </html:form></body></html>

We have used some Struts-specific Form tag like <html:form /> instead of HTML tags.

In the Form tags the attributes you can find some attributes defined in we will go through it.

action : Represents the URL to which this form will be submitted. This attribute is also used to find the appropriate ActionMapping in the Struts configuration file, which we will describe later in this section. The value used in our example is Name, which will map to an ActionMapping with a path attribute equal to Name. 

name :Identifies the key that the ActionForm will be referenced by. We use the value NameForm. An ActionForm is an object that is used by Struts to represent the form data as a JavaBean. It main purpose is to pass form data between View and Controller components. We will discuss NameForm later in this section. type :Names the fully qualified class name of the form bean to use in this request. For this example, we use thevalue example.NameForm, which is an ActionForm object containing data members matching the inputs of this form.

To use the HTML tags, you must first add a taglib entry in the application’s web.xml file that references the URI /WEB-INF/struts-html.tld. This TLD describes all of the tags in the HTML tag library. The following snippet shows the <taglib> element that must be added to the web.xml file:

<taglib>

 <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri><taglib-location>/WEB-INF/struts-html.tld</taglib-location>

</taglib>

The struts-html.tld is placed in the /WEB_INF directory.

Next Step is to create the action form

The ActionForm used in this example contains a single data member that maps directly to the name input parameter of the form defined in the index.jsp View. When an <html:form/> is submitted, the Struts framework populates the matching data members of the ActionForm with the values entered into the <html:input/> tags. The Struts framework does this by using JavaBean reflection. The accessors of the ActionForm must follow the JavaBean

Page 15: Java Notes

standard naming convention for example

private String name;public void setName(String name);public String getName(); 

The NameForm.java file is shown belowNameForm.java 

package example;//import statementsimport javax.servlet.http.HttpServletRequest;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionMapping;

public class NameForm extends ActionForm {

 private String name = null;public String getName() {

    return (name);

  }    public void setName(String name) {

    this.name = name;

  }    public void reset(ActionMapping mapping, HttpServletRequest request) {

    this.name = null;

  }  }

To deploy the NameForm to our Struts application, you need to compile this class, move it to the /WEB-INF/classes/example directory, and add the following line to the <form-beans> section of the /WEB-INF/struts-config.xml file:

<form-bean name="nameForm" type="example.NameForm"/>

This makes the Struts application aware of the NameForm and how it should be referenced. 

Now we create the out page for the sample application.Lets name it diplayname.jspdisplayname.jsp

<html><head><title>Sample Struts Display Name</title></head><body>

    <table width="80%" border="0">

      <tr>

        <td>Hello <%= request.getAttribute("NAME") %> !!</td>

      </tr>

Page 16: Java Notes

    </table></body></html>

Now we move to the step two of creating the application's controller

In a Struts application, two components make up the Controller. These two components are theorg.apache.struts.action.ActionServlet and the org.apache. struts.action.Action classes. In most Struts applications, there is one org. apache.struts.action.ActionServlet implementation and can have many org.apache. struts.action.Actionimplementations.

The org.apache.struts.action.ActionServlet is the Controller component that handles client requests and determines whichorg.apache.struts.action.Action will process the received request. When assembling simple applications, such as the one we are building, the default ActionServlet will satisfy your application needs, and therefore, you do not need to create a specializedorg.apache.struts.action.ActionServlet implementation. 

The second component of a Struts Controller is the org.apache.struts. action.Action class. As opposed to the ActionServlet, the Action class must be extended for each specialized function in your application. This class is where your application’s specific logic begins.NameAction.java

package example;

import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;

public class NameAction extends Action {

 public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {

   String target = new String("success");if ( form != null ) {

     // Use the NameForm to get the request parametersNameForm nameForm = (NameForm)form;String name = nameForm.getName();

    }  

   // if no mane supplied Set the target to failureif ( name == null ) {

      target = new String("failure");

    }

    else {

      request.setAttribute("NAME", name);

    }

Page 17: Java Notes

 return (mapping.findForward(target));}

}

Moving to step three, to deploy the NameAction to our Struts application, we need to compile the NameAction class and move the class file to /WEB-INF/classes/example directory, and add the following entry to the <action-mappings> section of the /WEB-INF/struts-config.xml file:

<action path="/Name" type="example.NameAction" name="nameForm" input="/index.jsp">

 <forward name="success" path="/displayname.jsp"/><forward name="failure" path="/index.jsp"/>

</action>

For step four we modify the web.xml file. We have to to tell the Web application about our ActionServlet. This is accomplished by adding the following servlet definition to the /WEB-INF/web.xml file:

<servlet>

 <servlet-name>action</servlet-name><servlet-class> org.apache.struts.action.ActionServlet </servlet-class> <init-param>

   <param-name>config</param-name><param-value>/WEB-INF/struts-config.xml</param-value>

  </init-param>

  <load-on-startup>1</load-on-startup></servlet>

Once we have told the container about the ActionServlet, we need to tell it when the action should be executed. To do this, we have to add a <servlet-mapping> element to the /WEB-INF/ web.xml file:

<servlet-mapping>

 <servlet-name>action</servlet-name><url-pattern>*.do</url-pattern>

</servlet-mapping>

You will notice in the previously listed index.jsp that our action does not include a .do at the end of the URL. We do not have to append the .do because it is automatically appended if we use the <html:form /> tag. If you do not use the <html:form /> tag, then you will need to append .do to the action's URL. This mapping tells the Web application that whenever a request is received with .do appended to the URL, the servlet named action should service the request.

Now you are ready to run the application, to begin using this application, you need to open your Web browser to the following URL:http://localhost:port/example/ 

Page 18: Java Notes

Struts Internationalization (i18n)Struts Internationalization (i18n) can be done with some handy modifications in our existing application. We have to know the two Internationalization (i18n) components that are packaged with the Struts Framework. The first of these components, which is managed by the application Controller, is a Message class that references a resource bundle containing Locale-dependent strings. The second Internationalization (i18n) component is a JSP custom tag, <bean:message />, which is used in the View layer to present the actual strings managed by the Controller.

In this section we will move with an example to understand the whole process. We are continuing the same example which we used earlier to understand the simple struts example in the section Struts Example.

First thing we will require for Internationalization (i18n) is a set of simple Java properties files. Each file contains a key/value pair for each message that you expect your application to present, in the language appropriate for the requesting client. 

This property file contains the key/value pairs for the default language of your application. The naming format for this file is ResourceBundleName.properties. An example of this default file, using English as the default language, would beApplicationResources.properties A sample entry in this file would be app.name=Name, this tells Struts that for every occurrence of the app.name key the Name will be substituted.

We must define a properties file for each language that your application will use. This file must follow the same naming convention as the default properties file, except that it must include the two-letter ISO language code of the language that it represents. Example of this naming convention For an German-speaking client would be ApplicationResources_de.properties For an French-speaking client would be ApplicationResources_fr.propertiesFor an Italian-speaking client would be ApplicationResources_it.propertiesFor an Spanish-speaking client would be ApplicationResources_es.properties 

Now add the respective entries in each properties files you require.

After you define all of the properties files for your application, you need to make Struts aware of them. It is achieved by adding a <message-resources> sub-element to the struts-config.xml file. Then you should copy all the resource bundles into the application classpath, /WEB-INF/classes/example, and then use the package path plus the base file name as the value of the <message-resources> subelement. The following snippet shows an example of using the <message-resources> subelement to configure a resource bundle, using the properties files described above

<message-resources parameter="example.ApplicationResources"/>

Once this part is done we customise the view part , this is achieved throught the second i18n component defined by the Struts Framework is a JSP custom tag, <bean:message />, which is used to present the actual strings that have been loaded by the Controller.

To use the <bean:message />, we must first deploy the bean tag library, which contains the <bean:message /> tag. Deploying a tag library is a very simple process that requires only the addition of a new <taglib> entry in the web.xml file of the Web application using the

Page 19: Java Notes

bean library. Here is an example of thisentry:

<taglib>

 <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri><taglib-location>/WEB-INF/struts-bean.tld</taglib-location>

</taglib>

Also check that the struts-bean.tld file is copied to the /WEB-INF/ folder.

<bean:message /> tag and how it is configured for use.

Now we are done we will check step by step of our saple application.

1. WeCreate the resource bundles that will contain the key/value pairs used in your application. For our application, we will have four properties files that contain our resource bundles. 

The German ApplicationResources_de.properties file.app.name=Nameapp.hello=Hallo

The French ApplicationResources_fr.properties file.app.name=Nomapp.hello=Bonjour

The Italian ApplicationResources_it.properties file.app.name=Nomeapp.hello=Ciao

The Spanish ApplicationResources_fr.properties file.app.name=Nombreapp.hello=Hola

The English ApplicationResources.properties file.app.name=Nameapp.hello=Hello

2. Copy all of the properties files to the /WEB-INF/classes/example directory.Add an application <message-resources /> subelement, naming the wiley. ApplicationResources to the struts-config.xml file, as shown

<struts-config>

  <form-beans>

    <form-bean name="nameForm" type="example.NameForm"/>

  </form-beans>

  <action-mappings>

    <action path="/Name" type="example.NameAction" name="NameForm" >

     <forward name="success" path="/quote.jsp"/><forward name="failure" path="/index.jsp"/>

    </action>

Page 20: Java Notes

  </action-mappings>

     <message-resources parameter="example.ApplicationResources"/></struts-config>

3. Modify the web.xml file as discussed above by adding

<taglib>

 <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri><taglib-location>/WEB-INF/struts-bean.tld</taglib-location>

</taglib>

4. Modify the index.jsp fileindex.jsp

<%@ page language="java" %><%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %><%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %><html><head><title>Sample Struts Application</title></head><body>

  <html:form action="Name" name="nameForm" type="example.NameForm">

    <table width="80%" border="0">

      <tr>

        <td><bean:message key="app.name" />:</td>

        <td><html:text property="name" /></td>

      </tr>

      <tr>

        <td><html:submit /></td>

      </tr>

    </table>

  </html:form></body></html>

Modify the diplayname.jspdisplayname.jsp

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %><html><head><title>Sample Struts Display Name</title></head><body>

    <table width="80%" border="0">

Page 21: Java Notes

      <tr>

       <td><bean:message key="app.hello" /><%= request.getAttribute("NAME") %> !!</td>

      </tr>

    </table></body></html>

So we are done with Internationalization (i18n) you need to open your Web browser to the following URL:http://localhost:port/example/ 

TILES

Introduction to Tiles

Tiles framework was previously called Components framework, Tiles is a open source framework for making the presentation layer work much easier by elimination of lot of rework and repeated codes. Tiles are very useful where a common look and feel among all pages are needed, tiles makes the code maintenance very easy, tiles makes a separation of layout from content

Tiles builds on the "include" feature provided by the JavaServer Pages specification thus letting you more feasibly create reusable pages. It helps to provide a full-featured, robust framework for assembling presentation pages from component parts. Each part ("Tile") can be reused as often as needed throughout your application. This reduces the amount of markup that needs to be maintained and makes it easier to change the look and feel of a website. You should think of tiles as visual components.

A tile layout is a special JSP page that allows tiles to be placed. Tile layouts dictate where the tiles will be laid out on the page. In many respects the tile layout resembles a template layout. In fact, if you have used Struts templates before, then you will note that the Tile framework is backwards compatible with the template custom tag library.

The Tiles framework's view components are known as tiles. The framework uses an XML configuration file to organize those tiles. This framework not only enables you to reuse tiles, but also the layouts that organize them.

To use Tiles in your project, you need following library :

tiles.jar commons-digester.jar commons-beanutils.jar commons-collections.jar tiles.tld

Web Page Layouts

1. JSP pages with embedded HTML

Page 22: Java Notes

The HTML is converted into JSP by embedding the code into the HTML. In this case each JSP has a duplicate header and footer and some common HTML codes. Problem with this type of Layouts is that changes in common view components, like header, footer and any of the common HTML codes occurring many of the pages , require changes in all relevant pages, as each page is responsible for laying out the view components. The number of pages decreases heavy maintenance cost. 

Example a site having pets information 

A JSP dog.jsp

<html>

  <body>

  Header

    Some description and pictures of dogs

  Footer

  </body></html>

Another JSP called cat.jsp

<html>

  <body>

  Header

    Some description and pictures of cats

  Footer

  </body></html>

2. JSP pages with JSP include directive's (static) or JSP actions (dynamic) 

This layouts separates layout from contents, JSP pages are reusable but layouts are not. You only need to change common view components once. Hence, this solution greatly eliminates HTML and JSP code repetition, significantly improving application maintainability. The drawbacks of this layout is each display page explicitly specifies where which JSP goes, if we want to change the content for the common JSP it ok but if we want to change the layout all the pages need to be changed.

dog.jsp<html><head><title>Templates</title></head><body background='images/grass.gif'><table width='610'><tr valign='top'><td><jsp:include page='sidemenu.jsp'/></td><td><table><tr><td><jsp:include page='header.html'/></td></tr><tr><td><jsp:include page='dog.jsp'/></td></tr><tr><td><jsp:include page='footer.jsp'/></td></tr></table></td>

Page 23: Java Notes

</tr></table></body></html>

cat.jsp<html><head><title>Templates</title></head><body background='images/grass.gif'><table width='610'><tr valign='top'><td><jsp:include page='sidemenu.jsp'/></td><td><table><tr><td><jsp:include page='header.html'/></td></tr><tr><td><jsp:include page='cat.jsp'/></td></tr><tr><td><jsp:include page='footer.html'/></td></tr></table></td></tr></table></body></html>

3. JSP templates 

We can use a Template that is a JSP page which uses JSP custom tag library to describe the layout of a page without specifying contents, in this layout the content is inserted into the template page during runtime, the advantage of this layout is that both content and layout can change without interfering each other, A single place to change when layout change is required, the drawback of the earlier layout which uses include is overcome and Template provides consistent look and feel without having to hard-code it in every page.

<%@ taglib URI='/WEB-INF/struts-template.tld' prefix='template' %><template:insert template='/defaultTemplate.jsp'><template:put name='title' content='Pets' direct='true'/><template:put name='header' content='/header.html'/><template:put name='sidebar' content='/sidemenu.jsp'/><template:put name='content' content='/dogs.jsp'/><template:put name='footer' content='/footer.html'/></template:insert>

4. Tiles

Tiles make the separation of layout from contents, JSP pages and Layouts are reusable, it is a superset of JSP templates with more features, it is extends concept of JSP templates with "parameterized components" or "Tiles"

Using Tiles's templating feature, you can define a layout say layout.jsp as a template. Since this is a layout, you insert placeholders instead of the actual view components using the Tiles insert tag. Thus, for all components, this page defines one reusable layout: 

<%@ taglib uri="/WEB-INF/tiles.tld" prefix="tiles" %><html><body><%-- include header --%><tiles:insert attribute="header"/><%-- include body --%>

Page 24: Java Notes

<tiles:insert attribute="body"/><%-- include footer --%><tiles:insert attribute="footer"/></body></html>

Other content pages, like dog.jsp and cat.jsp, use the above layout for arranging components. In the actual page, you insert the layout using the Tiles insert tag. Using the Tiles put tag, you can specify the actual view components for all placeholders specified in the layout. 

Consider this dog.jsp

<%@ taglib uri="/WEB-INF/tiles.tld" prefix="tiles" %><tiles:insert page="/layout.jsp" flush="true"><tiles:put name="header" value="/header.html"/><tiles:put name="body" value="/dog.jsp"/><tiles:put name="footer" value="/footer.html"/> </tiles:insert>

Consider this cat.jsp

<%@ taglib uri="/WEB-INF/tiles.tld" prefix="tiles" %><tiles:insert page="/layout.jsp" flush="true"><tiles:put name="header" value="/header.html/><tiles:put name="body" value="/cat.jsp"/><tiles:put name="footer" value="/footer.html"/> </tiles:insert>

Layouts

Tiles framework use a term “Layout” for a template. Layout serves the same purpose as template. The plus points of layouts is reusability of templates, we can define common layouts and reuse them across many different projects, even we can customize the existing layout

Pre-built Layouts from Tiles FrameworkHere we describe some useful layouts available in the Tiles distribution.

One interesting point of Tiles is that it is possible to reuse existing layouts, define new layouts, and easily exchange a layout by a different one as long as they require the same set of attributes.For each layout, a short description, a description of requested attributes, an example of usage and the actual implementation is provided. You can easily customize any layout by starting from the provided implementation. All layouts examples can be found in the /layouts directory of the Tiles example jar file. They can be tested by pointing to the /examples directory of the Tiles example jar file.

1. Classic layoutIt provides a classic"header, menu, body and footer" rendering. It defines the skeleton of a HTML page with <header> and <body>, and renders the header, menu, body and footer at appropriate places.The classic layout requires the following attributes:

Page 25: Java Notes

title - String used to set the title of the browser page.header - URL or definition name used to render the header part.

2. Menu layoutThe menu layout is used to render a simple menu with its links. A menu requires a list of "item" beans, each "item" contains data for one menu entry. It’s possible to develop other menu layouts taking the same attributes, and replace the menu layout by another one.The menu layout requires the following attributes:title - String used as menu title [optional]items - List of items. Items are beans with the following properties: value, link,tooltip; icon

3. Vertical box or vbox or vstack layoutThe vbox layout is used to render a list of Tiles vertically. This layout is used when rendering a menu bar, or in multi - columns layout.The vbox layout requires the following attributes:list - List of names or URLs to insert.

4. Multi-columns layoutThe multi-columns layout renders lists of Tiles in several columns stacked vertically. Lists of Tiles are passed as Tiles parameters, one list per column. A list can contain application URLs and definition names. This layout is used to build a portal main body made of several Tiles. The multi-columns layout requires the following attributes:numCols - Number of columns to render and passed as parameter.list1 - First list of Tiles (URL or definition name)list2 - Second list of Tiles (URL or definition name) [optional]list3 - Third list of Tiles (URL or definition name) [optional]listn - N-th list of Tiles (URL or definition name), where n is replaced by column index[optional].

5. Center layoutThe classical layout consisting of “top, left, center, right, bottom”. Left and right parts areoptional and can be omitted.The center layout requires the following attributes:header - URL or definition name used to render the header part.right - URL or definition name used to render the right part. [optional]body - URL or definition name used to render the header part.left - URL or definition name used to render the left part. [optional]footer - URL or definition name used to render the footer part.

6. Tabs layoutThe tabs layout is used to render a list of Tiles in a tab fashion. The tabs layout has a body area used to render the currently selected Tile, and an indexes area used to render the available tabs or Tiles. This layout requires as argument a list of Tiles and names used in indexes.The tabs layout requires the following attributes:tabList - A list of Tiles URLs or definition names for the tabs. We use MenuItem tocarry data (Tiles name or URL, indexes name, icon, ...).selectedIndex - Index of the default selected tab.parameterName - Name of HTTP parameter carrying the selected Tile info in the HTTPrequest.

Page 26: Java Notes

 

Installing Tiles

The Tiles installation process depends on the Struts version. Tiles can also be used without Struts. To enable Tiles definitions described in one or more files, you need to write these definition's files and to initialize the definition factory. If you don't use definitions, you don't need to initialize the factory.

For Struts1.0 

the required file are tilesForStruts1.0.jar – in WEB-INF/lib/tiles.tld – in WEB-INF/struts.jar, commons-digester.jar, commons-collections.jar, commons-beanutils.jar – in WEB-INF/lib/Struts related filesAll these files should come with the Tiles or Struts distribution. They are normally located in WEB-INF/lib/ for .JAR files and WEB-INF/ for .TLD files.

To Enable Definitions for Struts 1.0

You need to use a special servlet extending the Struts servlet. This is specified in the web.xml file of your application:<servlet><servlet-name>action</servlet-name><servlet-class>org.apache.struts.tiles.ActionComponentServlet</servlet-class><!-- Tiles Servlet parameter Specify configuration file names. There can be several comma separated file names--><init-param><param-name>definitions-config</param-name><param-value>/WEB-INF/tiles-defs.xml</param-value></init-param><!-- Tiles Servlet parameterSpecify if xml parser should validate the Tiles configuration file.true : validate. DTD should be specified in file header.false : no validation--><init-param><param-name>definitions-parser-validate</param-name><param-value>true</param-value></init-param>...</servlet>

If you have developed your own servlet extending the standard Struts servlet, consider extending the Tiles servlet instead, or provide methods and hooks enabling Tiles

For Struts1.1 

the required file are struts.jar – in WEB-INF/lib/. Tiles are now in the main Struts distribution.

Page 27: Java Notes

tiles.tld – in WEB-INF/all commons-*.jar files needed by Struts – in WEB-INF/lib/All these files should come with the Tiles or Struts distribution. They are normally located in WEB-INF/lib/ for .JAR files and WEB-INF/ for .TLD files.

<plug-in className="org.apache.struts.tiles.TilesPlugin" ><set-property property="definitions-config"value="/WEB-INF/tiles-defs.xml, /WEB-INF/tiles-tests-defs.xml,/WEB-INF/tiles-tutorial-defs.xml,/WEB-INF/tiles-examples-defs.xml" /><set-property property="moduleAware" value="true" /><set-property property="definitions-parser-validate" value="true" /></plug-in>

To Enable Definitions for Struts 1.1

Use the Tiles plug-in to enable Tiles definitions. This plug-in creates the definition factory and pass it a configuration object populated with parameters explained here after. Parameters can be specified in the web.xml file or as the plug-in parameters. The plug-in first read parameters from web.xml, and then overload them with the one found in the plug-in. All parameters are optional and can be omitted. The plug-in should be declared in each struts-config file:<plug-in className="org.apache.struts.tiles.TilesPlugin" ><set-property property="definitions-config"value="/WEB-INF/tiles-defs.xml,/WEB-INF/tiles-tests-defs.xml,/WEB-INF/tiles-tutorial-defs.xml,/WEB-INF/tiles-examples-defs.xml" /><set-property property="moduleAware" value="true" /><set-property property="definitions-parser-validate" value="true" /></plug-in>

For Tiles stand alone 

Required files are:tiles.jar – in WEB-INF/lib/tiles.tld – in WEB-INF/commons-digester.jar, commons-collections.jar, commons-beanutils.jar – in WEBINF/lib/All these files should come with the Tiles distribution. They are normally located in WEBINF/lib/ for .JAR files and WEB-INF/ for .TLD files.

To Enable Definitions for Tiles stand alone 

Tiles can be used without Struts. To initialize the definition factory, you can use the provided servlet. Declare it in the web.xml file of your application:<servlet><servlet-name>action</servlet-name><servlet-class>org.apache.struts.tiles.TilesServlet</servlet-class><init-param><param-name>definitions-config</param-name><param-value>/WEB-INF/tiles-defs.xml</param-value></init-param><init-param><param-name>definitions-parser-validate</param-name>

Page 28: Java Notes

<param-value>true</param-value></init-param>...The parameters are the same as for Struts1.1 or 1.0.

Configuring Tiles

Configure WEB-INF/web.xml file

<taglib><taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri><taglib-location>/WEB-INF/struts-tiles.tld</taglib-location></taglib>

Configure Tiles Plugin in struts-config.xml file

<plug-in className="org.apache.struts.tiles.TilesPlugin"><set-property property="definitions-config" value="/WEB-INF/tilesdefs. xml"/><set-property property="moduleAware" value="true"/><set-property property="definitions-parser-validate" value="true"/></plug-in>

Internationalizing Tiles

It is possible to load different Tiles according to the user's Locale

You can use all I18N capatibilities of Struts to internationalize your Tiles. But Tiles additionally provides a way to select a Tile according to the Java Locale (language and country) using definitions and definitions files/factories. you can have one definition file per Locale, the appropriate definition is loaded accordingto the current Locale

– tiles-definitions-en.xml– tiles-definitions-de.xml

Each factory is linked to (loaded from) a definition file. The default load mechanism allows files starting with the same name, but ending with a Locale suffix, as with Java *.properties files.

 

Create a Tile Layout

Lets us start with an example.

Page 29: Java Notes

We have two web pages say dog.jsp and cat.jsp

A JSP dog.jsp

<html>

  <body>Header

  <p>Some description and pictures of dogs

  <p>Footer <p>

  </body></html>Another JSP called cat.jsp

<html>

  <body>Header

  <p>Some description and pictures of cats

  <p>Footer <p>

  </body></html>

First thing you have to find the similarities and common between pages. Then you should create a new layout page

Create two new content pages that contain just the differences between dog.jsp and cat.jsp.

Insert the tile layout in the page -- that is, have dog.jsp and cat.jsp insert the tile layout into their page, passing the content as a parameter and any other necessary parameters (like Title).

We create newlayout page with the similarities between the dog.jsp and cat.jsp pages

To create a tile layout, you must do the following:

Import the tiles taglib into the JSP and any other taglibs you need with the taglibdirective.<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %><%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %><%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>

Use string parameters to display things like the page title using the tiles:getAsString tag. We can use string parameters to display things like the page title. You not only want to change the page's content, you also want to change the title that appears in thebrowser. To do so, pass in a title that the tile layout will use:

<html>

  <head>Header

 <title><tiles:getAsString name="title" ignore="true"/>

Page 30: Java Notes

  </head></html>Use the tiles:getAsString tag to display string parameters. We can not only pass string parameters but also we can pass other pages to be inserted into this page. That assumes the calling JSP page passes a title to this tile layout; otherwise, the title will be blank. The ignore attribute, if true, means ignore the attribute if missing. Otherwise, If ignore is false, the tiles framework will throw an exception and the page will not display if the parameter does not pass (false is the default).

Insert the tiles in the correct regions of the layout using the tiles:insert tag. To insert the content JSP, use the tiles:insert tag, which inserts any page or Web resource that the framework refers to as a tile. The tag effectively defines a region in the tile layout. Remember, the objective of the tile layout is to lay out the tiles into the layout. Here is an example of inserting a tile into the layout:

<tiles:insert attribute="content"/>

The example above is really simple. What if you want to insert a tile and pass it items in the current page scope? For example, it's possible to pass the title parameter (in tile scope) to header.jsp with the Tiles framework.

Pass any needed parameters to the internal tiles using tiles:put -- a subtag oftiles:insert. We can pass the tile parameters while we insert a tile. The parameter passes has the tile scope.

To use the tiles taglib, don't forget to include the tag library in your web.xml file:

<taglib><taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri><taglib-location>/WEB-INF/struts-tiles.tld</taglib-location></taglib>

complete code for the layout layout.jsp

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %><%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %><%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %><html>

  <head>

    <title>

   <tiles:getAsString name="title" ignore="true"/></title>

  </head>

  <body>

    <table >

      <tr>

        <td>

          <tiles:insert attribute="header" ignore="true">

Page 31: Java Notes

<tiles:put name="title" beanName="title" beanScope="tile"/></tiles:insert>

        </td>

      </tr>

   

<tr><td>

</td></tr></table>

      <tr>

        <td>

         <div align="center"><tiles:insert attribute="content"/></div>

        </td>

      </tr>

      <tr>

        <td>

          <tiles:insert attribute="footer" ignore="true"/>

        </td>

      </tr>

  <body></html>In the next section Use a Tile layout,we will see how to use this layout.

Use a Tile Layout

In the previous section we created a layout is common for both dog.jsp and cat.jsp , In this section we will see how we can use that layout for both dog.jsp and cat.jsp.

First sep is to Import the tiles taglib with the taglib directive.<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>

Second step is to Use tiles:insert to insert the tile layout into the current page.

<tiles:insert page="/layout.jsp" flush="true"><tiles:put name="title" type="string" value="DOG" /><tiles:put name="header" value="/header.jsp" /><tiles:put name="footer" value="/footer.jsp" /><tiles:put name="content" value="/dogContent.jsp"/></tiles:insert>

Third step is to Use tiles:put to pass string parameters.

<tiles:put name="title" type="string" value="Dog" />

Page 32: Java Notes

Notice how tiles:put passes string parameters to the tile layout. The tiles:put's name attribute tag specifies the parameter name. The tiles:put's type attribute specifies the parameter's type. Lastly, the value parameter is passed the title attribute's value. That lets you pass simple strings as parameters when the tile layout (display function) gets called with the tiles:insert tag. The parameters become tilelayout attributes; that is, they get inserted into the tile scope of the tile layout.

Fourth step is to Use tiles:put to pass in parameter tiles.

<tiles:put name="header" value="/header.jsp" /><tiles:put name="footer" value="/footer.jsp" /><tiles:put name="content" value="/dogContent.jsp"/>

Tile Definitions - Create a Tile Definition

A layout may include many regions and we may have to repeat the parameter every time we want to use a tile layout, it would be better if we define it at one place instead of in each page.

We invoke the tile layout using tiles:insert and pass in parameters using tiles:put. The parameters are other JSP pages and strings that can be inserted into regions of the tile layout. We now need the ability to define default parameters corresponding to the common regions regions. The Tiles framework also lets you pass default arguments to a tile layout using definitions.

Create and use a JSP definitionFirst import the tiles tag library using the taglib directive.<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %><%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>

Second ensure that the definition is defined only once using the logic:notPresent tag.<logic:notPresent name="layoutDef" scope="application">

Third define the definition with the tiles:definition tag passing the JSP page that defines the tile layout and the scope of the newly defined definition.<tiles:definition id="layoutDef" page="/layout.jsp" scope="application">

Fourth define the default parameters with the tiles:put tag.<tiles:put name="title" type="string" value="DOG" /><tiles:put name="header" value="/header.jsp" /><tiles:put name="footer" value="/footer.jsp" /><tiles:put name="content" type="string">Some details...</tiles:put></tiles:definition></logic:notPresent>

The tiles:definition tag defines a JavaBean component of type ComponentDefinition (org.apache.struts.tiles.ComponentDefinition). ComponentDefinition has getter and setters for all of the attributes that you can pass it. The logic:notPresent tag ensures that the

Page 33: Java Notes

ComponentDefinition is only created once per application by checking to see if it's already in scope before defining it.

Using a tile definition resembles using a tile layout directly. The only differences: you will specify the definition instead of the tile layout JSP page, and you will pass in less parameters with tiles:put.

Tile Definitions - Use a Tile DefinitionFirst import the tiles tag library with the taglib directive.<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>

Second include the JSP page that defines the definition with jsp:include.<jsp:include page="layoutDefinition.jsp"/>

Third use the tiles:insert tag, but specify the definition bean name and scope instead of the tile layout page.<tiles:insert beanName="layoutDef" beanScope="application"><tiles:put name="title" type="string"value="DOG DETAIL" /><tiles:put name="content" value="dogdetail.jsp"/></tiles:insert>

Fourth use the tiles:put attribute to specify title and content only.

HIBERNATE TUTORIAL

HIBERNATE - Introduction to Hibernate

Hibernate is an open source object/relational mapping tool for Java. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework. 

Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC. 

Hibernates goal is to relieve the developer from 95 percent of common data persistence related programming tasks.

Hibernate is Free Software. The LGPL license is sufficiently flexible to allow the use of Hibernate in both open source and commercial projects (see the LicenseFAQ for details). Hibernate is available for download at http://www.hibernate.org/. This tutorial aims to provide insight into Hibernate version 3.0RC and its usage

Some of the main features of hibernate are listed below and we have tried to explain some

Page 34: Java Notes

of them in detail later in this tutorial. 

  Transparent persistence without byte code processing    Transparent persistence    JavaBeans style properties are persisted    No build-time source or byte code generation / processing    Support for extensive subset of Java collections API    Collection instance management    Extensible type system    Constraint transparency    Automatic Dirty Checking    Detached object support  Object-oriented query language    Powerful object-oriented query language    Full support for polymorphic queries    New Criteria queries    Native SQL queries  Object / Relational mappings    Three different O/R mapping strategies    Multiple-objects to single-row mapping    Polymorphic associations    Bidirectional associations    Association filtering    Collections of basic types    Indexed collections    Composite Collection Elements    Lifecycle objects  Automatic primary key generation    Multiple synthetic key generation strategies    Support for application assigned identifiers    Support for composite keys  Object/Relational mapping definition    XML mapping documents    Human-readable format    XDoclet support  HDLCA (Hibernate Dual-Layer Cache Architecture)    Thread safeness    Non-blocking data access    Session level cache    Optional second-level cache    Optional query cache    Works well with others  High performance    Lazy initialization    Outer join fetching    Batch fetching    Support for optimistic locking with versioning/timestamping

Page 35: Java Notes

    Highly scalable architecture    High performance    No "special" database tables    SQL generated at system initialization time    (Optional) Internal connection pooling and PreparedStatement caching

HIBERNATE - Overview of Hibernate

High level architecture of Hibernate can be described as shown in following illustration.

Hibernate makes use of persistent objects commonly called as POJO (POJO = "Plain Old Java Object".) along with XML mapping documents for persisting objects to the database layer. The term POJO refers to a normal Java objects that does not serve any other special role or implement any special interfaces of any of the Java frameworks (EJB, JDBC, DAO, JDO, etc...).

Rather than utilize byte code processing or code generation, Hibernate uses runtime reflection to determine the persistent properties of a class. The objects to be persisted are defined in a mapping document, which serves to describe the persistent fields and associations, as well as any subclasses or proxies of the persistent object. The mapping documents are compiled at application startup time and provide the framework with necessary information for a class. Additionally, they are used in support operations, such as generating the database schema or creating stub Java source files.

Typical Hibernate code

Page 36: Java Notes

sessionFactory = new Configuration().configure().buildSessionFactory();

Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

Customer newCustomer = new Customer();newCustomer.setName("New Customer");newCustomer.setAddress("Address of New Customer");newCustomer.setEmailId("[email protected]");

session.save(newCustomer);

tx.commit();

session.close();First step is hibernate application is to retrieve Hibernate Session; Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate configurations file hibernate.cfg.xml.

After specifying transaction boundaries, application can make use of persistent java objects and use session for persisting to the databases.

HIBERNATE - Features of Hibernate

  Transparent persistence without byte code processing    Transparent persistence    JavaBeans style properties are persisted    No build-time source or byte code generation / processing    Support for extensive subset of Java collections API    Collection instance management    Extensible type system    Constraint transparency    Automatic Dirty Checking    Detached object support  Object-oriented query language    Powerful object-oriented query language    Full support for polymorphic queries    New Criteria queries    Native SQL queries  Object / Relational mappings    Three different O/R mapping strategies    Multiple-objects to single-row mapping    Polymorphic associations    Bidirectional associations    Association filtering    Collections of basic types    Indexed collections    Composite Collection Elements

Page 37: Java Notes

    Lifecycle objects  Automatic primary key generation    Multiple synthetic key generation strategies    Support for application assigned identifiers    Support for composite keys  Object/Relational mapping definition    XML mapping documents    Human-readable format    XDoclet support  HDLCA (Hibernate Dual-Layer Cache Architecture)    Thread safeness    Non-blocking data access    Session level cache    Optional second-level cache    Optional query cache    Works well with others  High performance    Lazy initialization    Outer join fetching    Batch fetching    Support for optimistic locking with versioning/timestamping    Highly scalable architecture    High performance    No "special" database tables    SQL generated at system initialization time    (Optional) Internal connection pooling and PreparedStatement caching  J2EE integration    JMX support    Integration with J2EE architecture (optional)    New JCA support

HIBERNATE - Getting Started With Hibernate

Hibernate is Free Software. The LGPL license is sufficiently flexible to allow the use of Hibernate in both open source and commercial projects (see the LicenseFAQ for details). Hibernate is available for download at http://www.hibernate.org/

We wll take up an simple java example that authenticates users based on the credentials to get started with hibernate.

HIBERNATE - Getting Started With Hibernate

Preparing Database

Let’s consider a simple database schema with a singe table as APPLABSUSER.

Page 38: Java Notes

CREATE TABLE `applabsuser` (`USER_ID` int(11) NOT NULL default '0',`USER_NAME` varchar(255) NOT NULL default '',`USER_PASSWORD` varchar(255) NOT NULL default '',`USER_FIRST_NAME` varchar(255) default NULL,`USER_LAST_NAME` varchar(255) default NULL,`USER_EMAIL` varchar(255) default NULL,`USER_CREATION_DATE` date default NULL,`USER_MODIFICATION_DATE` date default NULL,PRIMARY KEY (`USER_ID`),UNIQUE KEY `USER_NAME` (`USER_NAME`)) ;

Creating persistent java objects

Hibernate works best with the Plain Old Java Objects programming model for persistent classes. 

Hibernate is not restricted in its usage of property types, all Java JDK types and primitives (like String, char and Date) can be mapped, including classes from the Java collections framework. You can map them as values, collections of values, or associations to other entities. The id is a special property that represents the database identifer (primary key) of that class, Hibernate can use identifiers only internally, but we would lose some of the flexibility in our application architecture. 

No special interface has to be implemented for persistent classes nor do you have to subclass from a special root persistent class. Hibernate also doesn't require any build time processing, such as byte-code manipulation, it relies solely on Java reflection and runtime class enhancement (through CGLIB). So, without any dependency of the POJO class on Hibernate, we can map it to a database table. 

Following code sample represents a java object structure which represents the AppLabsUser table. Generally these domain objects contain only getters and setters methods. One can use Hibernate extension toolset to create such domain objects.

Page 39: Java Notes

AppLabsUser.java

package org.applabs.quickstart;

import java.io.Serializable;import java.util.Date;import org.apache.commons.lang.builder.ToStringBuilder;

public class AppLabsUser implements Serializable {   

public void setName(String name) {/** identifier field */private Long id;

/** persistent field */private String userName;

/** persistent field */private String userPassword;

/** persistent field */private String userFirstName;

/** persistent field */private String userLastName;

/** persistent field */private String userEmail;

/** persistent field */private Date userCreationDate;

/** persistent field */private Date userModificationDate;

/** full constructor */public Applabsuser(String userName, String userPassword, String userFirstName, String userLastName, String userEmail, Date userCreationDate, Date userModificationDate) {this.userName = userName;this.userPassword = userPassword;this.userFirstName = userFirstName;this.userLastName = userLastName;this.userEmail = userEmail;this.userCreationDate = userCreationDate;this.userModificationDate = userModificationDate;}

/** default constructor */public Applabsuser() {}

public Long getId() {

Page 40: Java Notes

return this.id;}

public void setId(Long id) {this.id = id;}

public String getUserName() {return this.userName;}

public void setUserName(String userName) {this.userName = userName;}

public String getUserPassword() {return this.userPassword;}

public void setUserPassword(String userPassword) {this.userPassword = userPassword;}

public String getUserFirstName() {return this.userFirstName;}

public void setUserFirstName(String userFirstName) {this.userFirstName = userFirstName;}

public String getUserLastName() {return this.userLastName;}

public void setUserLastName(String userLastName) {this.userLastName = userLastName;}

public String getUserEmail() {return this.userEmail;}

public void setUserEmail(String userEmail) {this.userEmail = userEmail;}

public Date getUserCreationDate() {return this.userCreationDate;}

public void setUserCreationDate(Date userCreationDate) {this.userCreationDate = userCreationDate;}

Page 41: Java Notes

public Date getUserModificationDate() {return this.userModificationDate;}

public void setUserModificationDate(Date userModificationDate) {this.userModificationDate = userModificationDate;}public String toString() {return new ToStringBuilder(this).append("id", getId()).toString();}

}// End of class

Mapping POJO with persistence layer using hibernate mapping document

Each persistent class needs to be mapped with its configuration file. Following code represents Hibernate mapping file for AppLabsUser class.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"><hibernate-mapping>

 <class name="org.applabs.hibernate.quickstart.AppLabsUser" table="applabsuser">

    <id column="USER_ID" name="id" type="java.lang.Long">

      <generator class="sequence"/>

    </id>

 

 <property column="USER_NAME" length="255" name="userName" not-null="true" type="java.lang.String"/><property column="USER_PASSWORD" length="255" name="userPassword" not-null="true" type="java.lang.String"/><property column="USER_FIRST_NAME" length="255" name="userFirstName" type="java.lang.String"/><property column="USER_LAST_NAME" length="255" name="userLastName" type="java.lang.String"/><property column="USER_EMAIL" length="255" name="userEmail" type="java.lang.String"/><property column="USER_CREATION_DATE" length="10" name="userCreationDate" type="java.util.Date"/><property column="USER_MODIFICATION_DATE" length="10" name="userModificationDate" type="java.util.Date"/>

  </class>

</hibernate-mapping> 

One can also generate Hibernate mapping documents using Hibernate extension toolset. Hibernate mapping documents are straight forward. The <class> element maps a table with

Page 42: Java Notes

corresponding class. The <id> element represents the primary key column, and its associated attribute in the domain object. The <property> elements represent all other attributes available in the domain object.

Hibernate Configuration File

Hibernate configuration file information needed to connect to persistent layer and the linked mapping documents. You can either specify the data source name or JDBC details that are required for hibernate to make JDBC connection to the database. The element <mapping-resource> refers to the mapping document that contains mapping for domain object and hibernate mapping document.

<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

  <session-factory>

 

  <property name="show_sql">true</property><property name="hibernate.dialect">org.hibernate.dialect.MySQLMyISAMDialect</property><property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property><property name="hibernate.connection.url">jdbc:mysql://localhost:3306/applabs</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">r00Tp@$wd</property>

<mapping resource="org/applabs/hibernate/quickstart/Applabsuser.hbm.xml"/>  </session-factory></hibernate-configuration> 

Hibernate Sample Code (Inserting new record)

Here is how you can use Hibernate in your programs. Typical Hibernate programs begin with configuration that is required for Hibernate. Hibernate can be configured in two ways. Programmatically and Configuration file based. In Configuration file based mode, hibernate looks for configuration file “hibernate.cfg.xml” in the claspath. Based on the resource mapping provided hibernate creates mapping of tables and domain objects. In the programmatic configuration method, the details such as JDBC connection details and resource mapping details etc are supplied in the program using Configuration API.

Following example shows programmatic configuration of hibernate.

 Configuration config = new Configuration().addResource("org/applabs/hibernate/quickstart/Applabsuser.hbm.xml")Configuration config = new Configuration().addClass(org.hibernate.quickstart.Applabsuser.class).setProperty("hibernate.dialect", "org.hibernate.dialect. MySQLMyISAMDialect").setProperty("hibernate.connection.driver_class", " org.gjt.mm.mysql.Driver")

Page 43: Java Notes

. . . SessionFactory sessions = config.buildSessionFactory();In configuration file based approach, “hibernate.cfg.xml” is placed in the classpath, Following Hibernate code can be used in this method.

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();Session session = sessionFactory.openSession();AppLabsUser user = new AppLabsUser();Transaction tx = session.beginTransaction();user.setUserCreationDate(new Date());user.setUserEmail("[email protected]");user.setUserFirstName("userFirstName");user.setUserLastName("userLastName");user.setUserName("userName-1");user.setUserPassword("userPassword");session.saveOrUpdate(user);tx.commit();session.close();

Hibernate Sample Code (Quering the database)

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();Session session = sessionFactory.openSession(); ArrayList arrayList = null;

String SQL_STRING = "FROM AppLabsUser as users";Query query = session.createQuery(SQL_STRING);ArrayList list = (ArrayList)query.list();

for(int i=0; i<list.size();i++){System.out.println(list.get(i));}

session.close();

HIBERNATE - Hibernate O/R Mapping

This section will explain how to write the mapping documents manually. Although there are tools available to create these mapping documents, learning how to create these documents manually helps in fine tuning and setting up advance table mapping.

Mapping Declaration

Object/relational mappings are usually defined in XML document. The mapping language is Java-centric, meaning that mappings are constructed around persistent class declarations, not table declarations.

Mapping Document<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

Page 44: Java Notes

<hibernate-mapping package="org.somepackage.eg">  <class name="Foo" table=”FooTable”>    <id name="id" type=”java.lang.Long”>      <generator class=”sequence”/>    </id>  </class></hibernate-mapping> 

The above example shows a typical mapping document that contains class mapping with table.All mapping XML document should refer to hibernate-mapping-3.0.dtd via doctype.

<hibernate-mapping> element

The root element of hibernate mapping document is <hibernate-mapping> element. This element has several optional attributes. The schema and catalog attributes specify that tables referred to in this mapping belong to the named schema and/or catalog. If specified, tablenames will be qualified by the given schema and catalog names. If missing, tablenames will be unqualified. The default-cascade attribute specifies what cascade style should be assumed for properties and Collections which do not specify a cascade attribute. The auto-import attribute lets us use unqualified class names in the query language, by default.

<hibernate-mapping

 

schema="schemaName" catalog="catalogName" default-cascade="cascade_style" default-access="field|property|ClassName" default-lazy="true|false" auto-import="true|false" package="package.name" 

(1)(2)(3)(4)(5)(6)(7)

/>  

(1) schema (optional): The name of a database schema.(2) catalog (optional): The name of a database catalog.(3) default-cascade (optional - defaults to none): A default cascade style.(4) default-access (optional - defaults to property): The strategy Hibernate should use for

accessing all properties. Can be a custom implementation of PropertyAccessor.(5) default-lazy (optional - defaults to true): The default value for unspecifed lazy

attributes of class and collection mappings.(6) auto-import (optional - defaults to true): Specifies whether we can use unqualified class

names (of classes in this mapping) in the query language.(7) package (optional): Specifies a package prefix to assume for unqualified class names in

the mapping document.

<class> element

The <Class> element maps the domain object with corresponding entity in the database. hibernate-mapping element allows you to nest several persistent <class> mappings, as shown above. It is however good practice to map only a single persistent class in one

Page 45: Java Notes

mapping file and name it after the persistent superclass, e.g. User.hbm.xml, Group.hbm.xml.

<class

 

name="ClassName"table="tableName"discriminator-value="discriminator_value" mutable="true|false" schema="owner" catalog="catalog"proxy="ProxyInterface" dynamic-update="true|false" dynamic-insert="true|false" select-before-update="true|false" polymorphism="implicit|explicit" where="arbitrary sql where condition" persister="PersisterClass" batch-size="N" optimistic-lock="none|version|dirty|all" lazy="true|false" entity-name="EntityName" catalog="catalog" check="arbitrary sql check condition" rowid="rowid" subselect="SQL expression" abstract="true|false" 

(1)(2)(3)(4)(5)(6)(7) (8)(9)(10)(11)(12)(13)(14)(15)(16)(17)(18)(19)(20)(21)(22)

/>  

(1) name (optional): The fully qualified Java class name of the persistent class (or interface). If this attribute is missing, it is assumed that the mapping is for a non-POJO entity.

(2) table (optional - defaults to the unqualified class name): The name of its database table.

(3) discriminator-value (optional - defaults to the class name): A value that distiguishes individual subclasses, used for polymorphic behaviour. Acceptable values include null and not null.

(4) mutable (optional, defaults to true): Specifies that instances of the class are (not) mutable.

(5) schema (optional): Override the schema name specified by the root <hibernate-mapping> element.

(6) catalog (optional): Override the catalog name specified by the root <hibernate-mapping> element.

(7) proxy (optional): Specifies an interface to use for lazy initializing proxies. You may specify the name of the class itself.

(8) dynamic-update (optional, defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed.

(9) dynamic-insert (optional, defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

(10) select-before-update (optional, defaults to false): Specifies that Hibernate should never perform an SQL UPDATE unless it is certain that an object is actually modified. In certain cases (actually, only when a transient object has been associated with a new

Page 46: Java Notes

session using update()), this means that Hibernate will perform an extra SQL SELECT to determine if an UPDATE is actually required.

(11) polymorphism (optional, defaults to implicit): Determines whether implicit or explicit query polymorphism is used.

(12) where (optional) specify an arbitrary SQL WHERE condition to be used when retrieving objects of this class

(13)persister (optional): Specifies a custom ClassPersister.

(14) batch-size (optional, defaults to 1) specify a "batch size" for fetching instances of this class by identifier.

(15) optimistic-lock (optional, defaults to version): Determines the optimistic locking strategy.

(16)lazy (optional): Lazy fetching may be completely disabled by setting lazy="false".

(17) entity-name (optional): Hibernate3 allows a class to be mapped multiple times (to different tables, potentially), and allows entity mappings that are represented by Maps or XML at the java level. In these cases, you should provide an explicit arbitrary name for the entity. See Section 4.4, “Dynamic models” for more information.

(18)catalog (optional): The name of a database catalog used for this class and its table.

(19) check (optional): A SQL expression used to generate a multi-row check constraint for automatic schema generation.

(20) rowid (optional): Hibernate can use so called ROWIDs on databases which support. E.g. on Oracle, Hibernate can use the rowid extra column for fast updates if you set this option to rowid. A ROWID is an implementation detail and represents the physical location of a stored tuple.

(21) subselect (optional): Maps an immutable and read-only entity to a database subselect. Useful if you want to have a view instead of a base table, but don't. See below for more information.

(22) abstract (optional): Used to mark abstract superclasses in <union-subclass> hierarchies.

<id> element

The <id> element defines the mapping from that property to the primary key column. Mapped classes must declare the primary key column of the database table. Most classes will also have a JavaBeans-style property holding the unique identifier of an instance. 

<id

 

name="propertyName" type="typename" column="column_name" unsaved-value="null|any|none|undefined|id_value" access="field|property|ClassName">

<generator class="generatorClass"/>

(1)(2)(3)(4)(5)

/> 

(1) name (optional): The name of the identifier property.

Page 47: Java Notes

(2) type (optional): A name that indicates the Hibernate type.(3) column (optional - defaults to the property name): The name of the primary key

column.(4) unsaved-value (optional - defaults to a "sensible" value): An identifier property value

that indicates that an instance is newly instantiated (unsaved), distinguishing it from detached instances that were saved or loaded in a previous session.

(5) access (optional - defaults to property): The strategy Hibernate should use for accessing the property value.

<generator> element

The optional <generator> child element names a Java class used to generate unique identifiers for instances of the persistent class. If any parameters are required to configure or initialize the generator instance, they are passed using the <param> element. 

<id name="id" type="long" column="cat_id">  <generator class="org.hibernate.id.TableHiLoGenerator">

    <param name="table">uid_table</param><param name="column">next_hi_value_column</param>

  </generator>

</id>

All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface; some applications may choose to provide their own specialized implementations. However, Hibernate provides a range of built-in implementations. There are shortcut names for the built-in generators: 

increment generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster. .

identity supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

sequence uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int

hilo uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database.

seqhilo uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.

uuid uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.

guid uses a database-generated GUID string on MS SQL Server and MySQL.native picks identity, sequence or hilo depending upon the capabilities of the

underlying database.assigned lets the application to assign an identifier to the object before save() is called.

This is the default strategy if no <generator> element is specified.select retrieves a primary key assigned by a database trigger by selecting the row by

some unique key and retrieving the primary key valueforeign uses the identifier of another associated object. Usually used in conjunction with

a <one-to-one> primary key association.

Page 48: Java Notes

<property> element

The <property> element declares a persistent, JavaBean style property of the class.

<property

 

name="propertyName" column="column_name"type="typename" update="true|false" insert="true|false" formula="arbitrary SQL expression" access="field|property|ClassName"lazy="true|false" unique="true|false" not-null="true|false" optimistic-lock="true|false" 

(1)(2)(3)(4)(4)(5)(6)(7) (8)(9)(10)

/> 

All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface; some applications may choose to provide their own specialized implementations. However, Hibernate provides a range of built-in implementations. There are shortcut names for the built-in generators: 

(1) name: the name of the property, with an initial lowercase letter.(2) column (optional - defaults to the property name): the name of the mapped database

table column. This may also be specified by nested <column> element(s).(3) type (optional): a name that indicates the Hibernate type.(4) update, insert (optional - defaults to true) : specifies that the mapped columns should

be included in SQL UPDATE and/or INSERT statements. Setting both to false allows a pure "derived" property whose value is initialized from some other property that maps to the same colum(s) or by a trigger or other application.

(5) formula (optional): an SQL expression that defines the value for a computed property. Computed properties do not have a column mapping of their own.

(6) access (optional - defaults to property): The strategy Hibernate should use for accessing the property value.

(7) lazy (optional - defaults to false): Specifies that this property should be fetched lazily when the instance variable is first accessed (requires build-time bytecode instrumentation).

(8) unique (optional): Enable the DDL generation of a unique constraint for the columns. Also, allow this to be the target of a property-ref.

(9) not-null (optional): Enable the DDL generation of a nullability constraint for the columns.

(10) optimistic-lock (optional - defaults to true): Specifies that updates to this property do or do not require acquisition of the optimistic lock. In other words, determines if a version increment should occur when this property is dirty.

typename could be:

The name of a Hibernate basic type (eg. integer, string, character, date, timestamp, float, binary, serializable, object, blob).

The name of a Java class with a default basic type (eg. int, float, char, java.lang.String, java.util.Date, java.lang.Integer, java.sql.Clob).

Page 49: Java Notes

The name of a serializable Java class. The class name of a custom type (eg. com.illflow.type.MyCustomType).

An especially powerful feature are derived properties. These properties are by definition read-only, the property value is computed at load time. You declare the computation as a SQL expression, this translates to a SELECT clause subquery in the SQL query that loads an instance: 

<property name="totalPrice"formula="( SELECT SUM (li.quantity*p.price) FROM LineItem li, Product p

 WHERE li.productId = p.productIdAND li.customerId = customerIdAND li.orderNumber = orderNumber )"/>

<many-to-one> element

An ordinary association to another persistent class is declared using a many-to-one element. The relational model is a many-to-one association: a foreign key in one table is referencing the primary key column(s) of the target table. 

<many-to-one

 

name="propertyName" column="column_name" class="ClassName" cascade="cascade_style" fetch="join|select" update="true|false"insert="true|false" property-ref="propertyNameFromAssociatedClass"access="field|property|ClassName"unique="true|false"not-null="true|false" optimistic-lock="true|false"lazy="true|false" entity-name="EntityName"

(1)(2)(3)(4)(5)(6)(6)(7) (8)(9)(10)(11) (12)

/> 

(1) name: The name of the property.(2) column (optional): The name of the foreign key column. This may also be specified by

nested <column> element(s).(3) class (optional - defaults to the property type determined by reflection): The name of

the associated class.(4) cascade (optional): Specifies which operations should be cascaded from the parent

object to the associated object.(5) join (optional - defaults to select): Chooses between outer-join fetching or sequential

select fetching.(6) update, insert (optional - defaults to true) specifies that the mapped columns should be

included in SQL UPDATE and/or INSERT statements. Setting both to false allows a pure "derived" association whose value is initialized from some other property that maps to

Page 50: Java Notes

the same colum(s) or by a trigger or other application.(7) property-ref: (optional) The name of a property of the associated class that is joined to

this foreign key. If not specified, the primary key of the associated class is used.

(8) access (optional - defaults to property): The strategy Hibernate should use for accessing the property value.

(9) unique (optional): Enable the DDL generation of a unique constraint for the foreign-key column. Also, allow this to be the target of a property-ref. This makes the association multiplicity effectively one to one.

(10) not-null (optional): Enable the DDL generation of a nullability constraint for the foreign key columns.

(11) optimistic-lock (optional - defaults to true): Specifies that updates to this property do or do not require acquisition of the optimistic lock. In other words, dertermines if a version increment should occur when this property is dirty.

(12) lazy (optional - defaults to false): Specifies that this property should be fetched lazily when the instance variable is first accessed (requires build-time bytecode instrumentation).

A typical many-to-one declaration looks as simple as this:

<many-to-one name="product" class="Product" column="PRODUCT_ID"/>

<one-to-one> element

A one-to-one association to another persistent class is declared using a one-to-one element. . 

<one-to-one

 

name="propertyName" (1)class="ClassName" (2)cascade="cascade_style" (3)constrained="true|false" (4)fetch="join|select" (5)property-ref="propertyNameFromAssociatedClass" (6)access="field|property|ClassName" (7)formula="any SQL expression" (8)entity-name="EntityName"

(1)(2)(3)(4)(5)(6)(7) (8)

/> 

(1) name: The name of the property.(2) class (optional - defaults to the property type determined by reflection): The name of

the associated class.(3) cascade (optional) specifies which operations should be cascaded from the parent

object to the associated object.(4) constrained (optional) specifies that a foreign key constraint on the primary key of the

mapped table references the table of the associated class. This option affects the order in which save() and delete() are cascaded, and determines whether the association may be proxied (it is also used by the schema export tool).

(5) fetch (optional - defaults to select): Chooses between outer-join fetching or sequential select fetching.

(6) property-ref: (optional) The name of a property of the associated class that is joined to

Page 51: Java Notes

the primary key of this class. If not specified, the primary key of the associated class is used.

(7) access (optional - defaults to property): The strategy Hibernate should use for accessing the property value.

(8) formula (optional): Almost all one to one associations map to the primary key of the owning entity. In the rare case that this is not the case, you may specify a some other column, columns or expression to join on using an SQL formula. (See org.hibernate.test.onetooneformula for an example.)

A typical many-to-one declaration looks as simple as this:

<many-to-one name="product" class="Product" column="PRODUCT_ID"/>

HIBERNATE - Hibernate Mapping In Depth

Hibernate allows the mapping of Mapped tables with the domain objects using the persistent collection-valued fields. These fields needs be declared as an interface type. The actual interface can be java.util.Set, java.util.Collection, java.util.List, java.util.Map, java.util.SortedSet, java.util.SortedMap or custom implementations of org.hibernate.usertype.UserCollectionType

Collections instances have the usual behavior of value types. They are automatically persisted when referenced by a persistent object and automatically deleted when unreferenced. If a collection is passed from one persistent object to another, its elements might be moved from one table to another. Two entities may not share a reference to the same collection instance. Due to the underlying relational model, collection-valued properties do not support null value semantics; 

public class Product {

 

private String serialNumber;private Set parts = new HashSet();public Set getParts() { return parts; }void setParts(Set parts) { this.parts = parts; }public String getSerialNumber() { return serialNumber; }void setSerialNumber(String sn) { serialNumber = sn; }

}Collection Mapping

<map  name="propertyName" 

table="table_name" schema="schema_name"lazy="true|false" inverse="true|false"cascade="all|none|save-update|delete|all-delete-orphan" 

sort="unsorted|natural|comparatorClass" order-by="column_name asc|desc" where="arbitrary sql where condition" fetch="join|select" batch-size="N" access="field|property|ClassName" optimistic-lock="true|false" 

(1)(2)(3)(4)(5)(6)(7) (8)(9)(10)(11)(12)(13)

Page 52: Java Notes

>

<key .... /><map-key .... /><element .... />

</map> 

(1) name the collection property name

(2) table (optional - defaults to property name) the name of the collection table (not used for one-to-many associations)

(3) schema (optional) the name of a table schema to override the schema declared on the root element

(4) lazy (optional - defaults to true) enable lazy initialization (not available for arrays)

(5) inverse (optional - defaults to false) mark this collection as the "inverse" end of a bidirectional association

(6) cascade (optional - defaults to none) enable operations to cascade to child entities

(7)sort (optional) specify a sorted collection with natural sort order, or a given comparator class

(8)order-by (optional, JDK1.4 only) specify a table column (or columns) that define the iteration order of the Map, Set or bag, together with an optional asc or desc

(9)where (optional) specify an arbitrary SQL WHERE condition to be used when retrieving or removing the collection (useful if the collection should contain only a subset of the available data)

(10)fetch (optional, defaults to select) Choose between outer-join fetching and fetching by sequential select. Only one collection may be fetched by outer join per SQL SELECT.

(11)batch-size (optional, defaults to 1) specify a "batch size" for lazily fetching instances of this collection.

(12)access (optional - defaults to property): The strategy Hibernate should use for accessing the property value.

(13)optimistic-lock (optional - defaults to true): Species that changes to the state of the collection results in increment of the owning entity's version. (For one to many associations, it is often reasonable to disable this setting.)

These are some more mapings which we will discuss later

Association MappingComponent MappingInstance Mapping

HIBERNATE - Hibernate Query Language

Hibernate is equipped with an extremely powerful query language that looks very much like SQL. Queries are case-insensitive, except for names of Java classes and properties.

Clause

The from clause

Page 53: Java Notes

The simplest possible Hibernate query is of the form: 

From org.applabs.base.UserFrom User

which simply returns all instances of the class org.applabs.base.User. 

Most of the time, you will need to assign an alias, since you will want to refer to the User in other parts of the query.

from User as user

This query assigns the alias user to User instances, so we could use that alias later in the query. The as keyword is optional; we could also write:

from User user

Multiple classes may appear, resulting in a cartesian product or "cross" join. 

from User, Groupfrom User as user, Group as group

The select clause

The select clause picks which objects and properties to return in the query result set. Queries may return properties of any value type including properties of component type: 

select user.name from User userwhere user.name like 'mary%'

select customer.contact.firstName from Customer as cust

The where clause

The where clause allows you to narrow the list of instances returned. 

from User as user where user.name='mary'

returns instances of User named 'mary'. 

Compound path expressions make the where clause extremely powerful. Consider: 

from org.applabs.base.Customer cust where cust.contact.name is not null

This query translates to an SQL query with a table (inner) join. If you were to write something like The = operator may be used to compare not only properties, but also instances: 

from Document doc, User user where doc.user.name = user.name

The special property (lowercase) id may be used to reference the unique identifier of an

Page 54: Java Notes

object. (You may also use its property name.) 

from Document as doc where doc.id = 131512

from Document as doc where doc.author.id = 69

The order by clause

The list returned by a query may be ordered by any property of a returned class or components: 

from User user order by user.name asc, user.creationDate desc, user.email

The optional asc or desc indicate ascending or descending order respectively. 

The group by clause

A query that returns aggregate values may be grouped by any property of a returned class or components: 

select sum(document) from Document document group by document.category

A having clause is also allowed. 

select sum(document) from Document document group by document.categoryhaving document.category in (Category.HIBERNATE, Category.STRUTS)

Associations and joins

We may also assign aliases to associated entities, or even to elements of a collection of values, using a join. The supported join types are borrowed from ANSI SQL • inner join • left outer join • right outer join • full join (not usually useful) 

The inner join, left outer join and right outer join constructs may be abbreviated. 

Aggregate functions

HQL queries may even return the results of aggregate functions on properties: The supported aggregate functions are 

avg(...), sum(...), min(...), max(...) , count(*), count(...), count(distinct ...), count(all...) The distinct and all keywords may be used and have the same semantics as in SQL. 

Expressions

Expressions allowed in the where clause include most of the kind of things you could write in SQL: • mathematical operators +, -, *, / • binary comparison operators =, >=, <=, <>, !=, like 

Page 55: Java Notes

• logical operations and, or, not • string concatenation || • SQL scalar functions like upper() and lower() • Parentheses ( ) indicate grouping • in, between, is null • JDBC IN parameters ? • named parameters :name, :start_date, :x1 • SQL literals 'foo', 69, '1970-01-01 10:00:01.0' • Java public static final constants eg.Color.TABBY 

Sub queries

For databases that support subselects, Hibernate supports subqueries within queries. A subquery must be surrounded by parentheses (often by an SQL aggregate function call). Even correlated subqueries (subqueries that refer to an alias in the outer query) are allowed.

HIBERNATE - Hibernate Complete Example

In this section we will extend our quick start sample into to a web based application that comprises of struts and Hibernate support.

IntroductionIn this example we will build a simple web based document repository application using hibernate. The document repository under consideration will have categorization of the documents based on the topics (Folder based like structure), Keywords for each document (this will simplify searches), versioning for each document, Document modification history, permissions based access for each entity based on users and groups.

Database scheme.The concept of properties tables: Here we have extended the concept of Hash tables to the database, Instead of adding more and more columns as per growing needs A properties table is created per Entity, Each property (Prop) table contains name and value pair that stores additional information for particular entity, thus you can store as many properties as you want for a given entity. Getter and setter methods need to be provided from the domain object so that we can represent these properties inside domain objects.

Basic entities.Basic entities such as User, Group, and Permissions along with Prop tables for each are provided to persistent data for corresponding entities, Now as a business rule a group contains multiple Users and One User can be a part of multiple Groups. Each entity, User, Group, and Permission have UserProp, GroupProp and PremissionProp respectively. The relation between Entity and Prop is one to many. E.g. User can have multiple Properties. (For simplicity, Permission tables are not shown in the model)

Categories and DocumentsCategory refers to a Folder/Directory like structure on the file system. Each category may or may not have its Parent Category. Category contains information like name, description, creation details, modification deleted and deletion details. Each category can have multiple entries. (Each Folder can contain one or more Documents (Entries) in it. Each Document can have one or more versions in it.(Document corresponds to version). Document contains information such as Title, Body, Summary, life cycle details, version number, keywords, workflow status, Entry details and Attachment details; Document also contains properties associated with it. Attachment is a file associated with each Document, Database stores the

Page 56: Java Notes

name of file stored on the file system and the size of Attachment.

Database Scripts

 

--Drop TablesDROP TABLE "APP"."ATTACHMENT";DROP TABLE "APP"."CATEGORY";DROP TABLE "APP"."CATEGORY_PROP";DROP TABLE "APP"."DOCUMENT";DROP TABLE "APP"."DOCUMENT_ATTACHMENT";DROP TABLE "APP"."DOCUMENT_KEYWORDS";DROP TABLE "APP"."DOCUMENT_PROP";DROP TABLE "APP"."ENTRY";DROP TABLE "APP"."GROUP";DROP TABLE "APP"."GROUP_PROP";DROP TABLE "APP"."IDGENERATOR";DROP TABLE "APP"."KEYWORD";DROP TABLE "APP"."USER";DROP TABLE "APP"."USER_GROUP";DROP TABLE "APP"."USER_PROP";

-- Table: "APP"."ATTACHMENT"CREATE TABLE "APP"."ATTACHMENT"("ATTACHMENT_ID" numeric NOT NULL,"DOCUMENT_ID" numeric,"ATTACHMEMT_PATH" varchar,"ATTACHMENT_SIZE" numeric,CONSTRAINT "ATTACHMENT_pkey" PRIMARY KEY ("ATTACHMENT_ID"));

-- Table: "APP"."CATEGORY"CREATE TABLE "APP"."CATEGORY"("CATAGORY_ID" numeric NOT NULL,"CATEGORY_NAME" varchar,"CATEGORY_DESCRIPTION" varchar,"CREATED_BY" numeric,"CREATION_DATE" date,"MODIFIED_BY" numeric,"MODIFICATION_DATE" date,"DELETED_BY" numeric,"DELETE_DATE" date,"PARENT_CATAGORY" numeric,CONSTRAINT "CATEGORY_pkey" PRIMARY KEY ("CATAGORY_ID"),CONSTRAINT "CATEGORY_PARENT_CATAGORY_fkey" FOREIGN KEY ("PARENT_CATAGORY") REFERENCES "APP"."CATEGORY" ("CATAGORY_ID") ON UPDATE NO ACTION ON DELETE NO ACTION,CONSTRAINT authorfk FOREIGN KEY ("CREATED_BY") REFERENCES "APP"."USER" ("USER_ID") ON UPDATE NO ACTION ON DELETE NO ACTION,CONSTRAINT deletorfk FOREIGN KEY ("DELETED_BY") REFERENCES "APP"."USER" ("USER_ID") ON UPDATE NO ACTION ON DELETE NO ACTION,

Page 57: Java Notes

CONSTRAINT editorfk FOREIGN KEY ("MODIFIED_BY") REFERENCES "APP"."USER" ("USER_ID") ON UPDATE NO ACTION ON DELETE NO ACTION);

-- Table: "APP"."CATEGORY_PROP"CREATE TABLE "APP"."CATEGORY_PROP"("CATEGORY_PROP_ID" numeric NOT NULL,"CATEGORY_ID" numeric,"PROP_NAME" varchar,"PROP_VALUE" varchar,CONSTRAINT "CATEGORY_PROP_pkey" PRIMARY KEY ("CATEGORY_PROP_ID"),CONSTRAINT "CATEGORY_PROP_CATEGORY_ID_fkey" FOREIGN KEY ("CATEGORY_ID") REFERENCES "APP"."CATEGORY" ("CATAGORY_ID") ON UPDATE NO ACTION ON DELETE NO ACTION);

-- Table: "APP"."DOCUMENT"CREATE TABLE "APP"."DOCUMENT"("DOCUMENT_ID" numeric NOT NULL,"DOCUMENT_TITLE" varchar,"DOCUMENT_BODY" varchar,"DOCUMENT_SUMMARY" varchar,"CREATED_BY" numeric,"CREATION_DATE" date,"MODIFIED_BY" numeric,"MODIFICATION_DATE" date,"DELETED_BY" numeric,"DELETED_DATE" date,"DOCUMENT_VERSION" numeric,"DOCUMENT_STATUS" numeric,"ENTRY_ID" numeric,CONSTRAINT "DOCUMENT_pkey" PRIMARY KEY ("DOCUMENT_ID"),CONSTRAINT "DOCUMENT_ENTRY_ID_fkey" FOREIGN KEY ("ENTRY_ID") REFERENCES "APP"."ENTRY" ("ENTRY_ID") ON UPDATE NO ACTION ON DELETE NO ACTION,CONSTRAINT authorfk FOREIGN KEY ("CREATED_BY") REFERENCES "APP"."USER" ("USER_ID") ON UPDATE NO ACTION ON DELETE NO ACTION,CONSTRAINT deletorfk FOREIGN KEY ("DELETED_BY") REFERENCES "APP"."USER" ("USER_ID") ON UPDATE NO ACTION ON DELETE NO ACTION,CONSTRAINT editorfk FOREIGN KEY ("MODIFIED_BY") REFERENCES "APP"."USER" ("USER_ID") ON UPDATE NO ACTION ON DELETE NO ACTION);

-- Table: "APP"."DOCUMENT_ATTACHMENT"CREATE TABLE "APP"."DOCUMENT_ATTACHMENT"("DOCUMENT_ATTACHMENT_ID" numeric NOT NULL,"ATTACHMENT_ID" numeric,"DOCUMENT_ID" numeric,"ATTACHMENT_PATH" varchar,"ATTACHMENT_SIZE" numeric,CONSTRAINT "DOCUMENT_ATTACHMENT_pkey" PRIMARY KEY ("DOCUMENT_ATTACHMENT_ID"),

Page 58: Java Notes

CONSTRAINT "DOCUMENT_ATTACHMENT_ATTACHMENT_ID_fkey" FOREIGN KEY ("ATTACHMENT_ID") REFERENCES "APP"."ATTACHMENT" ("ATTACHMENT_ID") ON UPDATE NO ACTION ON DELETE NO ACTION,CONSTRAINT "DOCUMENT_ATTACHMENT_DOCUMENT_ID_fkey" FOREIGN KEY ("DOCUMENT_ID") REFERENCES "APP"."DOCUMENT" ("DOCUMENT_ID") ON UPDATE NO ACTION ON DELETE NO ACTION);

-- Table: "APP"."DOCUMENT_KEYWORDS"CREATE TABLE "APP"."DOCUMENT_KEYWORDS"("DOCUMENT_KEYWORD_ID" numeric NOT NULL,"DOCUMENT_ID" numeric,"KEYWORD_ID" numeric,z CONSTRAINT "DOCUMENT_KEYWORDS_pkey" PRIMARY KEY ("DOCUMENT_KEYWORD_ID"),CONSTRAINT "DOCUMENT_KEYWORDS_DOCUMENT_ID_fkey" FOREIGN KEY ("DOCUMENT_ID") REFERENCES "APP"."DOCUMENT" ("DOCUMENT_ID") ON UPDATE NO ACTION ON DELETE NO ACTION,CONSTRAINT keywordidfk FOREIGN KEY ("KEYWORD_ID") REFERENCES "APP"."KEYWORD" ("KEYWORD_ID") ON UPDATE NO ACTION ON DELETE NO ACTION);

-- Table: "APP"."DOCUMENT_PROP"CREATE TABLE "APP"."DOCUMENT_PROP"(document_prop_id numeric NOT NULL,document_id numeric NOT NULL,prop_name varchar NOT NULL,prop_value varchar,prop_value_details varchar,CONSTRAINT "DOCUMENT_PROP_pkey" PRIMARY KEY (document_prop_id),CONSTRAINT "DOCUMENT_PROP_document_id_fkey" FOREIGN KEY (document_id) REFERENCES "APP"."DOCUMENT" ("DOCUMENT_ID") ON UPDATE NO ACTION ON DELETE NO ACTION);

-- Table: "APP"."ENTRY"CREATE TABLE "APP"."ENTRY"("ENTRY_ID" numeric NOT NULL,"CATEGORY_ID" numeric,CONSTRAINT "ENTRY_pkey" PRIMARY KEY ("ENTRY_ID"),CONSTRAINT "ENTRY_CATEGORY_ID_fkey" FOREIGN KEY ("CATEGORY_ID") REFERENCES "APP"."CATEGORY" ("CATAGORY_ID") ON UPDATE NO ACTION ON DELETE NO ACTION);

-- Table: "APP"."GROUP"CREATE TABLE "APP"."GROUP"("GROUP_ID" numeric NOT NULL,"GROUP_NAME" varchar,"GROUP_DESCRIPTION" varchar,"CREATED_BY" numeric,"CREATION_DATE" date,

Page 59: Java Notes

"MODIFIED_BY" numeric,"MODIFICATION_DATE" date,"DELETED_BY" numeric,"DELETE_DATE" date,CONSTRAINT "GROUP_ID_pk" PRIMARY KEY ("GROUP_ID") USING INDEX TABLESPACE apptablespace);

-- Table: "APP"."GROUP_PROP"CREATE TABLE "APP"."GROUP_PROP"(group_prop_id numeric NOT NULL,group_id numeric NOT NULL,prop_name varchar NOT NULL,prop_value varchar,prop_value_details varchar,CONSTRAINT "GROUP_PROP_pkey" PRIMARY KEY (group_prop_id),CONSTRAINT "GROUP_PROP_group_id_fkey" FOREIGN KEY (group_id) REFERENCES "APP"."GROUP" ("GROUP_ID") ON UPDATE NO ACTION ON DELETE NO ACTION);-- Table: "APP"."IDGENERATOR"CREATE TABLE "APP"."IDGENERATOR"(id numeric NOT NULL,next_value numeric NOT NULL,CONSTRAINT "IDGENERATOR_pkey" PRIMARY KEY (id));

-- Table: "APP"."KEYWORD"CREATE TABLE "APP"."KEYWORD"("KEYWORD_ID" numeric NOT NULL,"KEYWORD_NAME" varchar,"KEYWORD_DESCRIPTION" varchar,CONSTRAINT "KEYWORD_pkey" PRIMARY KEY ("KEYWORD_ID"));

-- Table: "APP"."USER"CREATE TABLE "APP"."USER"("USER_ID" numeric NOT NULL,"USER_NAME" varchar,"USER_PASSWORD" varchar,"USER_FIRST_NAME" varchar,"USER_LAST_NAME" varchar,"CREATION_DATE" date,"CREATED_BY" numeric,"MODIFICATION_DATE" date,"MODIFIED_BY" numeric,

Page 60: Java Notes

"DELETE_DATE" date,"DELETED_BY" numeric,CONSTRAINT "USER_pkey" PRIMARY KEY ("USER_ID"));

-- Table: "APP"."USER_GROUP"CREATE TABLE "APP"."USER_GROUP"("USER_GROUP" numeric NOT NULL,"USER_ID" numeric,"GROUP_ID" numeric,CONSTRAINT "USER_GROUP_pkey" PRIMARY KEY ("USER_GROUP"),CONSTRAINT "USER_GROUP_GROUP_ID_fkey" FOREIGN KEY ("GROUP_ID") REFERENCES "APP"."GROUP" ("GROUP_ID") ON UPDATE NO ACTION ON DELETE NO ACTION,CONSTRAINT "USER_GROUP_USER_ID_fkey" FOREIGN KEY ("USER_ID") REFERENCES "APP"."USER" ("USER_ID") ON UPDATE NO ACTION ON DELETE NO ACTION);

-- Table: "APP"."USER_PROP"CREATE TABLE "APP"."USER_PROP"(user_prop_id numeric NOT NULL,user_id numeric NOT NULL,prop_name varchar NOT NULL,prop_value varchar,prop_value_details varchar,CONSTRAINT "USER_PROP_pkey" PRIMARY KEY (user_prop_id),CONSTRAINT "USER_PROP_user_id_fkey" FOREIGN KEY (user_id) REFERENCES "APP"."USER" ("USER_ID") ON UPDATE NO ACTION ON DELETE NO ACTION);

Page 61: Java Notes

hbm files

User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>  <class name="org.applabs.base.User" table="USER">

    <id column="USER_ID" name="id" type="java.lang.Long">

      <generator class="org.hibernate.id.TableHiLoGenerator">

       <param name="table">idgen</param><param name="column">NEXT</param>

      </generator>

    </id>

    <property column="USER_NAME" name="userName" type="java.lang.String"/><property column="USER_PASSWORD" name="userPassword" type="java.lang.String"/><property column="USER_FIRST_NAME" name="userFirstName" type="java.lang.String"/><property column="USER_EMAIL" name="userEmail" type="java.lang.String"/><property column="USER_LAST_NAME" name="userLastName" type="java.lang.String"/><property column="CREATION_DATE" length="4" name="creationDate" type="java.util.Date"/>

Page 62: Java Notes

<property column="CREATED_BY" name="createdBy" type="java.lang.Double"/><property column="MODIFICATION_DATE" length="4" name="modificationDate" type="java.util.Date"/><property column="MODIFIED_BY" name="modifiedBy" type="java.lang.Double"/><property column="DELETE_DATE" length="4" name="deleteDate" type="java.util.Date"/><property column="DELETED_BY" name="deletedBy" type="java.lang.Double"/><set name="properties" lazy="true" inverse="true" cascade="all-delete-orphan">

     <key column="USER_ID" /><one-to-many class="org.applabs.base.UserProp" />

    </set>

  </class></hibernate-mapping>

UserProp.hbm.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>  <class name="org.applabs.base.UserProp" table="USER_PROP">    <id column="USER_PROP_ID" name="id" type="java.lang.Long">      <generator class="org.hibernate.id.TableHiLoGenerator">

        <param name="table">idgen</param><param name="column">NEXT</param>

      </generator>    </id>

   

<property column="CATEGORY_NAME" name="categoryName" type="java.lang.String"/><property column="CATEGORY_DESCRIPTION" name="categoryDescription" type="java.lang.String"/><property column="CREATED_BY" name="createdBy" type="java.lang.Double"/><property column="CREATION_DATE" length="4" name="creationDate" type="java.util.Date"/><property column="MODIFIED_BY" name="modifiedBy" type="java.lang.Double"/><property column="MODIFICATION_DATE" length="4" name="modificationDate" type="java.util.Date"/><property column="DELETED_BY" name="deletedBy" type="java.lang.Double"/><property column="DELETE_DATE" length="4" name="deleteDate" type="java.util.Date"/><!—- One way of implementing --><!-- <property column="PARENT_CATAGORY" name="parentCatagory" type="java.lang.Long"/> --><!—- Another way of One-to-many Mapping --><set name="childCatagories">

      <key column="CATAGORY_ID" not-null="true"/><one-to-many class="org.applabs.base.Category"/>

    </set>    <set name="properties" lazy="true" inverse="true" cascade="all-delete-orphan">

      <key column="CATEGORY_ID" /><one-to-many class="org.applabs.base.CategoryProp" />

    </set>  </class>

Page 63: Java Notes

</hibernate-mapping>

Category.hbm.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>  <class name="org.applabs.base.Category" table="CATEGORY">    <id column="CATAGORY_ID" name="id" type="java.lang.Long">      <generator class="org.hibernate.id.TableHiLoGenerator">

        <param name="table">idgen</param><param name="column">NEXT</param>

      </generator>    </id>

   

<property column="CATEGORY_NAME" name="categoryName" type="java.lang.String"/><property column="CATEGORY_DESCRIPTION" name="categoryDescription" type="java.lang.String"/><property column="CREATED_BY" name="createdBy" type="java.lang.Double"/><property column="CREATION_DATE" length="4" name="creationDate" type="java.util.Date"/><property column="MODIFIED_BY" name="modifiedBy" type="java.lang.Double"/><property column="MODIFICATION_DATE" length="4" name="modificationDate" type="java.util.Date"/><property column="DELETED_BY" name="deletedBy" type="java.lang.Double"/><property column="DELETE_DATE" length="4" name="deleteDate" type="java.util.Date"/><!—- One way of implementing --><!-- <property column="PARENT_CATAGORY" name="parentCatagory" type="java.lang.Long"/> --><!—- Another way of One-to-many Mapping --><set name="childCatagories">

      <key column="CATAGORY_ID" not-null="true"/><one-to-many class="org.applabs.base.Category"/>

    </set>    <set name="properties" lazy="true" inverse="true" cascade="all-delete-orphan">

      <key column="CATEGORY_ID" /><one-to-many class="org.applabs.base.CategoryProp" />

    </set>  </class></hibernate-mapping>

CategoryProp.hbm.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>  <class name="org.applabs.base.CategoryProp" table="CATEGORY_PROP">    <id column="CATEGORY_PROP_ID" name="id" type="java.lang.Long">      <generator class="org.hibernate.id.TableHiLoGenerator">

Page 64: Java Notes

        <param name="table">idgen</param><param name="column">NEXT</param>

      </generator>    </id>

   <property column="CATEGORY_ID" name="categoryId" type="java.lang.Long"/><property column="PROP_NAME" name="propName" type="java.lang.String"/><property column="PROP_VALUE" name="propValue" type="java.lang.String"/>

    </set>  </class></hibernate-mapping>

Document.hbm.xml 

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>  <class name="org.applabs.base.Document" table="DOCUMENT">    <id column="DOCUMENT_ID" name="id" type="java.lang.Long">      <generator class="sequence"/>    </id>

   

<property column="DOCUMENT_TITLE" name="documentTitle" type="java.lang.String"/><property column="DOCUMENT_BODY" name="documentBody" type="java.lang.String"/><property column="DOCUMENT_SUMMARY" name="documentSummary" type="java.lang.String"/><property column="CREATED_BY" length="65535" name="createdBy" type="java.lang.Double"/><property column="CREATION_DATE" length="4" name="creationDate" type="java.util.Date"/><property column="MODIFIED_BY" length="65535" name="modifiedBy" type="java.lang.Double"/><property column="MODIFICATION_DATE" length="4" name="modificationDate" type="java.util.Date"/><property column="DELETED_BY" length="65535" name="deletedBy" type="java.lang.Double"/><property column="DELETED_DATE" length="4" name="deletedDate" type="java.util.Date"/><property column="DOCUMENT_VERSION" length="65535" name="documentVersion" type="java.lang.Double"/><property column="DOCUMENT_STATUS" length="65535" name="documentStatus" type="java.lang.Double"/><property column="ENTRY_ID" length="65535" name="entryId" type="java.lang.Double"/>

  </class></hibernate-mapping>

DocumentProp.hbm.xml 

<?xml version="1.0" encoding="UTF-8"?>

Page 65: Java Notes

<!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>  <class name="org.applabs.base.DocumentProp" table="DOCUMENT_PROP">    <id column="document_prop_id" name="id" type="java.lang.Long">      <generator class="sequence"/>    </id>

   

<property column="document_id" length="65535" name="documentId" not-null="true" type="java.lang.Double"/><property column="prop_name" name="propName" not-null="true" type="java.lang.String"/><property column="prop_value" name="propValue" type="java.lang.String"/><property column="prop_value_details" name="propValueDetails" type="java.lang.String"/>

  </class></hibernate-mapping>