Monday, July 14, 2008

iBATIS tutorial: iBATIS in 10 minutes

IBatis is cross language query mapped engine. Solution available in Java,.NET,Ruby.
For quick learning, assume it as wrapper over JDBC.
It start with

1. Giving names to queries, passing parameters

<select id="getStudentRecord" parameterclass="StudentInformation" resultclass="StudentRecordDO">
</select>

1.1 We give name to student record fetching query as "getStudentRecord". So whenever we call getStudentRecord, we are actually calling this query.

1.2 Now we are passing studentId as parameter Here parameterClass="StudentInformation" means that Class studentInformation is passed as parameter and its member variable name will be used as parameter in this query. So studentId will be at StudentInformation->studentId.

1.3 Result are stored in resultClass i.e. StudentRecord may have member variables

StudentRecord->studentId
StudentRecord->name
StudentRecord->address
StudentRecord->joiningDate

These variable automatically get populated as result of query(Please not that order of students may be different but name should be same)

If names are different than we can use resultMap as

<resultmap id="MyMapId" class="MyClass">
<result property="MyClassMemberVariable column=" dbcolumn="">
</result>


only change will be instead of resultClass we will use resultMap



2. Setting all attributes in XML
2.1. We give alias to handle classes

<typealias alias="StudentRecord" type="com.helpdevelopers.iBatisExample.domain.StudentRecordDO">

so basically "com.helpdevelopers.iBatisExample.domain.StudentRecordDO" is the class used as resultClass in our named query(getStudentRecord).

2.2 We provide loose coupling and namespace for easily dividing queries.
Now wrapping all such named queries in XML files.

skeleton:


<sqlmap namespace="studentZone">
<!-- My Named queries will be placed here -->
</sqlmap>


Now assume that fileName is "studentInformation.xml".
2.3 We provide configuration details for JDBC use.





<sqlmapconfig>

<transactionmanager type="JDBC" commitrequired="true">
<datasource type="JDBC">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver"> <!-- Driver Name -->
<property name="JDBC.ConnectionURL" value="jdbc:mysql://studentDBServer:3306/Student">
<property name="JDBC.Username" value="student"> <!-- username and password to access DB -->
<property name="JDBC.Password" value="student">
</datasource >
</transactionmanager >

<sqlmap resource="iBatisQueryFiles/studentInformation.xml">

</sqlmap>
</sqlmapconfig>


Here all parameters are already used for JDBC connection so driver, url, userName, password etc. are assumed to be know to user. Briefly driver is connector name to bridge JDBC-DB gap, url is link of active DB server, username and password are authentic credentials to access that DB.
See, we easily binded our file studentInformation.xml by providing relative path.
Save file as sqlMapper.xml.

That's all. Setup complete.

3. Binding all together.

Now using that iBatis instance..(Java example)
3.1. Download iBatis for Java

3.2. put iBatis jar file at your projects build path i.e. include it in your classpath when compiling.

3.3 Instantiate iBatis Mapper, have connection class as


Its singleton implementation, you can choose your.


public class DAOFactory{

private SqlMapClient sqlMapper=null;

Reader queryReader=null;

private static DAOFactory factory;

// method returns an instance of sqlmapclient
private DAOFactory()
{
try{
queryReader= Resources.getResourceAsReader("sqlMapper.xml");
//Giving path of sqlMapper.xml to start with
sqlMapper = SqlMapClientBuilder.buildSqlMapClient(queryReader);
// executing chained XML's and collect all at sqlMapper
}
catch (Exception e) {
....... your exception code

}
}
public static DAOFactory getInstance()
{
if(factory==null)
{
factory=new DAOFactory(); //returning instance of Factory method
}
return factory;

}
public SqlMapClient getSQLMapper(){

//return the sqlmapper
return sqlMapper; // getting sqlMapper, whenever required.
}

}

That's all. Now calling would be

DAOFactory factory=DAOFactory.getInstance();

SqlMapper sqlMapper=factory.getSQLMapper();

sqlMapper.queryForObjects("getStudentRecord",studentInformation);

this will return null if student not found or object of StudentRecordDO
we can fetch list of records using
sqlMapper.queryForList(queryName,parameters);


We can also use update,delete, insert,select tag to define type of query operation like

<insert id="insertNewStaff" parameterclass="StaffInformation">
Your Insert Query..
</insert>

to call
sqlMapper.insert("insertNewStaff",StaffInformation).



4. Add-Ons:

4.1. Caching->iBatis provide database level caching. You can define cache-model as setting
cacheModelsEnabled="true", it also include many concepts including lazy loading and self pooling mechanism.

To use cache model we will use
cacheModel tag at XML.


4.2 Dyamic Queries:
iBatis is quite good in reducing your query efforts.
You can provide conditional tags, iterations and many more using iBatis.


iBatis for .net lovers at friendly blog

Saturday, April 12, 2008

Struts tutorial: Struts 1.x in 10 minutes

Preliminary knowledge of JSP/Servlet and web application required. Please visit
http://struts.apache.org/primer.html

Struts is framework implementation of MVC architecture for building web application in J2EE. It built on concept of JSP/Servlet.

In short, struts takes user input from JSP and populate data in actionForms(consist of beans) and provide that inputs to Actions(which perform main operations) by using session and request parameters. After that, we render necessary response using JSP enriched by struts tag library.
For configuration, we use struts-config.xml to bind JSP, forms and action together.

General Terms:

ActionController(struts-config.xml) is controlled by user. it contain mapping and declaration for all form beans, actions, resources, plug-ins, exception handling, error handling etc. This ActionController is fed to ActionServlet which helps in customizing struts based web application.
We use object of ActionMapping for relations defined.

Action Forms=> ActionForms are form beans consist of setters and getter of requested parameters from/to JSP.
Struts try to map html request parameters to action form associated with that display(JSP), struts automatically try to convert request parameter to actionform bean compatible format(like String,Integer,Time,Date etc.).

Action=> Action are performed after value submission from particular JSP/ActionForward, In general, actions are associated with ActionForm which automatically populated and passed as a parameter to Action. Mapping of actions are defined in action controller. Actions are mediator to perform particular operation provided by user input page.



Sessions=> Sessions are automatically maintained by JSP(to avoid @page session=false). In general we use session for passing list/population actionform/messages etc. For this, create instance of that session variable, populate necessary data and save it to session by using
request.getSession().setAttribute("myForm", populatedForm);
here myForm must be defined with same name in struts-config "name attribute" i.e.
under form beans section
<form-bean
name="myForm"
=>Name of Form Bean
type="com.mycompany.myproject.forms.MyForm"/> =>l Type of Form Bean
and actions are

<action
path="/printAction"> -> Action Name provided at JSP
name="myForm" => Name of Form Bean
input="/pages/inputword.jsp" => Input Page in case of error
type="com.mycompany.myproject.actions.PrintAction"/> =>Actual Mapped Action Class
scope="session"> => Defined Scope
<forward
name ="success" => Forward Name to be used in action

path="/pages/printword.jsp" => redirection after success
redirect="true"/>>
<action>






Tag Library:

Tag library are basic components for rendering JSP and providing certain inputs to Actions. It is part of best practices. It is having
property=name corresponding to ActionForm
name= name of form bean which is having that property(By default, JSP is having access to actionforms defined for that page, so for actionform attributes name may not be compulsory)
type: java class which defines type of particular form mean corresponding to given name and property
General Tags:
html:text => generate text box
html:select=>generate combo box
associated with html:optionsCollection or html:options which generate necessary options for that select statement.
html:textarea=>generate text area
html:submit=>submit Form which calls Action at end.
html:reset =>reset form
html:form=> form defination similar to html form tag having action parameter
html:checkbox=> generate checkbox
html:multibox =>generate multiple checkboxes
For using tags, tag library should in included in each JSP.



To generate output

bean:write=> to write particular bean to JSP
logic:iterate=> Used for iteration on basis of particular value defined by name and property, it will generate bean of name given in id attribute.

here id is form bean generated one by one, is part of property myRecordVOs of bean "myForm".
i.e. myList is of type RecordDisplayVO and myRecordVOs is collection of RecordDisplayVO


examples

<%@ taglib uri="/WEB-INF/struts-bean" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-html" prefix="html"%>
<%@ taglib uri="/WEB-INF/struts-logic" prefix="logic"%>
<body>

<html:text name="registerForm" property="UserName" tabindex="0" maxlength="50" styleId='userName'
>
<html:textbox name="registerForm" property="Comment" >

<html:select property="typeList" styleId="typeCombo">

<html:optionsCollection property="types" value="typeId" label="typeName"/>
<html:option>Others</html:option>
</html:select>



</body>

here types is Form Bean defined in default actionForm
label is displayed at front end and value picked up and provided to form.



To generate error messages
use input parameter in struts-config to select error page for particular action.Create object of ActionMessages and return mapping.getInputForward(); by action
on jsp end

automatically print error message
Error Messages are generally put in a property file say (MessageResource.properties) having key value pairs like
errors.required={0} is missing.
Here {0} is first input parameter provided in creating errorMessage.
example:

Write in Action:

ActionMessage errorMessage=new ActionMessage("errors.required","name entry");
errorMessages.add(ActionErrors.GLOBAL_MESSAGE, errorMessage);
saveErrors(request,errorMessages);
mapping.getInputForward();

It should generate,
"name entry is missing" in JSP in place of html errors.


To create application using struts, best way to start with IDE.
Create a web project, add struts library to that project. That's all.
For quick learning, refer to existing examples or start with struts-blank application.


Monday, March 05, 2007

OCEAN OF INFORMATION

OCEAN OF INFORMATION AND BOOKS(FREEINFOZ)
Warning: The site is not tested by our team. So please take care while surfing.