Tuesday, March 31, 2009

Hibenate Coding Steps

Steps to Code Hibenate :
1.Edit hibernate.cfg.xml :
Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment. Add an Entry for ???.hbm.xml

2.Create Table in databse

3.Create POJO Class which contains getter and setter method

4.Map Table Column vs POJO Class in .hbm.xml

5.Write Client Program

SessionFactory factory=null;
Session ses=null;
Transaction tx=null;
try
{ factory=new Configuration().configure().buildSessionFactory();
ses=factory.openSession();
tx = ses.beginTransaction();
ses.save(emp);
tx.commit();
}
catch (Exception e)
{
}

Monday, March 30, 2009

JavaScript

How to set Select a particular value when Select box is loaded?

1.Find Length of Select Box.
document.mtstafftransferform.qualification.options.length
2.Loop through
a)get the value of combobox
var val = document.mtstafftransferform.qualification.options[i].value;
b)match option value with value whihc needs to selected.
3.If matches
select the value selected
document.mtstafftransferform.qualification.selectedIndex=i;


Example :

<SCRIPT language=JavaScript type=text/javascript>
var qualify ="MATHS";
var comp_len = document.mtstafftransferform.qualification.options.length;
for (i=0; i<comp_len; i++)
{
var val = document.mtstafftransferform.qualification.options[i].value;
alert(""+val);
if(val == qualify)
{
document.mtstafftransferform.qualification.selectedIndex=i;
}
}
</SCRIPT>

Thursday, March 26, 2009

Tuesday, March 17, 2009

Hibernate Important Interview Question

1.What is O-R Mapping?
2.What is the difference between createCriteria and createQuery in Hibernate?
3.How would you implement on deletecasecade in Hiberante?
4.How Inheritance Implemented in Hiberante?
5.Is one Bean class can be involved with more than one relationship?
For example 1 class may have 1 to 1 and 1 to many
6.How do define compound primary key?
7.How to implement Oncasecasde deletion?
8.What is cascade="all"

Code Examples :

What are the steps to be followed to implement 1 to 1 database insert/update/delete?

Pre - Request :
Check we able to connect databse through Sample JSP program.

Step 1:

Table and Bean :

Create master table and Child table
Create bean for Master and Child table. Here Both Bean should contain gettter and setter value of other bean.


XML Entry :

In Master

Apart from XML Entry, There should be map to child table

<one-to-one name="<<Childtablename>>" class="<<ChildtableClass>>" cascade="all" />

<one-to-one name="employeeSalary" class="EmployeeSalary" cascade="all" />

Note : it refers only the class

In Child table

refer the master table's as below

In reference key column,

a)metioned generator class =foreign then mention property name
b)define one to one with property name and Class

Friday, March 13, 2009

EXCEL MACRO

a. Code for connecting to the excel file
Sub connectivity()
On Error GoTo myerr:
Set cn1 = New ADODB.Connection
With cn1
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source='" & ThisWorkbook.FullName & "'; Extended Properties=Excel 8.0;"
.Open
End With
myerr:
If Err.Number <> 0 Then
MsgBox Err.Description
End If
End Sub

B. Code for reading the datas from the excel file
Sub readingrecord()
connectivity
Set rs = New ADODB.Recordset
rs.Open "select * from [sheet1$]", cn1, adOpenStatic, adLockOptimistic
If rs.EOF = False Then
rs.MoveFirst
Do While Not rs.EOF
myName = rs.Fields(1).Value & "," & rs.Fields(2).Value
Set rs1 = New ADODB.Recordset
rs1.Open "select * from [sheet1$] where [Namefield] ='" & myName & "'", cn1, adOpenStatic, adLockOptimistic
If rs1.EOF = True Then
Sheet7.Cells(i, 1) = myName
Sheet7.Cells(i, 2) = 0
i = i + 1
End If
rs.MoveNext
Loop
End If
End sub

C. Code for save the data to the external excel file.
Sub fileupload()
Sheets("sheet1").Select
Cells.Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
ActiveWorkbook.SaveAs Filename:= _
"C:\test.xls", FileFormat:=xlNormal, _
Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, _
CreateBackup:=False
Sheets("Sheet1").Select
Sheets("Sheet1").Name = "sheet1"
Range("C8").Select
ActiveWorkbook.Save
ActiveWorkbook.Close
Range("A1").Select
End Sub

Thursday, March 12, 2009

SQL Server Back Up and Restoration

. Installation of SQL Server Database:
Click on SQLeval.exe.
Once the extraction is complete, click on setup.bat
Follow the below Instruction and complete the database server Installation.






1

2

3


4


5


Password as ehr/ehr

SQL Server Installation completed.
Configure DSN :
Start the database.
Click on SQL Server Enterprise Manager.
Expand the top most node.
Right click on database and click on New Database.
Create two databases core_db and core_db_session and note down the location of the data file and log file in both the cases.

Right click on core_db and click on All tasks menu. Click on Restore Database.
Click on From Device button as shown below in Fig 23
Fig 23:


Locate the core_db file and core_db_session file as shown below in Fig 24.
Fig 24:



On doing this, the following screen as shown below in Fig 25
will get displayed :

Click on Options tab and provide the locations of data file and the log files whose location was recorded in the previous steps and as shown below in Fig 26.
Fig 26:


Click on Ok button. The message will get displayed as shown below in Fig 27.
Fig 27



8. Configuration of Datasource:



Go to Control Panel. Click on Administrative tools / DataSources. On doing so a popup window will appear as shown below in Fig 28.
Fig 28:


Click on System DSN tab as shown below in Fig 29.
Fig 29:


Click on Add button. A popup screen similar to the one shown below in Fig 30
will appear .
Fig 30:


Select SQL Server and click on Finish Button. On Doing so another popup screen will get displayed as shown below in Fig 31
Fig 31:


Fill the data source name and select the server as shown above. Click on Next button
And fill the login id as well as the password. Use sa as login id and password as ehr
Fig 32:


Click on Next button and the following screen as shown below in Fig 33 will get displayed.


Fig 33


Click on Next button and the screen as shown below in Fig 34 will get displayed.
Fig 34:



Click on Finish.
Test the DSN Set up

Similarly create another datasource core_db_session.

Wednesday, March 11, 2009

My Code Link

Hi Friends

Here I have attached some of the samples I have developed

Please use it wherever is it required.

The Link is :MY CODES

XML Code GEN

XML & XSL EXAMPLE

<?xml version="1.0"?>

<?xml-stylesheet type="text/xsl" href="Input.xsl"?>

<project>
<class>
<type>private</type>
<Name>AddTwasdsoNumbers</Name>
</class>
<variable>
<var>
<type> int </type>
<Name>x</Name>
</var>
<var>
<type> int </type>
<Name>y</Name>
</var>

</variable>
<funtionmodule>
<var>
<Name>addtwonumber</Name>
<arg>
<type> int </type>
<Name>x</Name>
</arg>
<arg>
<type> int </type>
<Name>y</Name>
</arg>
<returntype> int </returntype>
</var>
</funtionmodule>

</project>

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<xsl:call-template name="project_class"/>
</body>
</html>
</xsl:template>

<xsl:template name="project_class">

<xsl:value-of select="project/class/type" disable-output-escaping="no"/>
<font color="red">class <xsl:value-of select="project/class/Name" disable-output-escaping="no"/> {
<br/></font> <div/>
<xsl:call-template name="project_Variable"/>
<br/>
<xsl:call-template name="project_Methods"/>
<br/>
}
</xsl:template>


<xsl:template name="project_Variable">

<xsl:for-each select="project/variable/var">

<xsl:value-of select="type" disable-output-escaping="no"/>

<xsl:value-of select="Name"/>
<br/>

</xsl:for-each>



</xsl:template>

<xsl:template name="project_Methods">
<xsl:for-each select="project/funtionmodule/var">
public <xsl:value-of select="returntype" disable-output-escaping="no"/> <xsl:value-of select="Name"/>() thrwos Exception{
<br/>
Rajnikanth

}
</xsl:for-each>


</xsl:template>


</xsl:stylesheet><!-- Stylus Studio meta-information - (c) 2004-2006. Progress Software Corporation. All rights reserved.
-->





Another Example :

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="emp.xsl"?>

<database name="scott">
<table-name name="Employee">
<fields>
<column-name>empid</column-name>
<column-type>number</column-type>
<column-size>5</column-size>
</fields>
<fields>
<column-name>empname</column-name>
<column-type>varchar</column-type>
<column-size>5</column-size>
</fields>
</table-name>
<table-name name="Student">
<fields>
<column-name>studentid</column-name>
<column-type>number</column-type>
<column-size>5</column-size>
</fields>
<fields>
<column-name>studentname</column-name>
<column-type>varchar</column-type>
<column-size>5</column-size>
</fields>
</table-name>
</database>


<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="html"/>

<xsl:template match="/">


<html>
<body>



<xsl:for-each select="database/table-name">
<table>
<tr>
<td><h4>Table Name:</h4></td><td><xsl:value-of select="@name"/></td>
</tr>
</table>
<table>
<tr width="250">
<th width="100">Name</th>
<th width="100">Type</th>
<th width="50">Size</th>
</tr>
<xsl:for-each select="fields">
<tr>
<td>
<xsl:value-of select="column-name"/>
</td>
<td>
<xsl:value-of select="column-type"/>
</td>
<td>
<xsl:value-of select="column-size"/>
</td>
</tr>
</xsl:for-each>
</table>
<br/>
<br/>
<br/>
</xsl:for-each>

========================
form submition
========================

<xsl:for-each select="database/table-name">
Table:<xsl:value-of select="@name"/>
<table>


<xsl:for-each select="fields">
<tr>

DB EMP NAME :<xsl:value-of select="column-name"/> :
USEREMPNAME :

<input type="text">
<xsl:attribute name="value"> <xsl:value-of select="column-name"/>
</xsl:attribute>
</input>
</tr>

</xsl:for-each>
</table>
</xsl:for-each>

</body>
</html>
</xsl:template>

</xsl:stylesheet>

Code Gen

Add Code Gen by JSP and then Convert to PHP

Java XML Example

import java.io.StringWriter;
import java.util.ArrayList;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.xerces.dom.DocumentImpl;
import org.w3c.dom.Document;
import org.w3c.dom.Element;


/**
* @author tzg136
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class XMLCreator {
Document xmlDoc = null;
Element rootElement = null;
Element topElement = null;
public Document getData()
{
xmlDoc = new DocumentImpl();
topElement = xmlDoc.createElement("source");

//data
ArrayList alEmp = new ArrayList();
EmployeeBean e= new EmployeeBean();
e.setEmp_ID("3636");
e.setEmp_Name("Andrew");
e.setEmp_Sal("60000");
alEmp.add(e);
e.setEmp_ID("2");
e.setEmp_Name("kumas");
e.setEmp_Sal("60asd000");
alEmp.add(e);

// data end

for(int i=0;i < alEmp.size();i++)
{
EmployeeBean emp = (EmployeeBean)alEmp.get(i);
createXml(emp);
}
System.out.println("TOP SIZE"+alEmp.size());
xmlDoc.appendChild(topElement);
System.out.println("OP NN"+xmlDoc.getNodeName());
System.out.println("OP"+xmlDoc.toString());
return xmlDoc;
}
public void createXml(EmployeeBean emp)
{
Element innnerElement = xmlDoc.createElement("EMPINFO");
org.w3c.dom.Node node_Empid = xmlDoc.createElement("Empid");
org.w3c.dom.Node node_EmpName = xmlDoc.createElement("EmpName");
org.w3c.dom.Node node_EmpSal = xmlDoc.createElement("EmpAge");

node_Empid.appendChild(xmlDoc.createTextNode(emp.getEmp_ID()));
node_EmpName.appendChild(xmlDoc.createTextNode(emp.getEmp_Name()));
node_EmpSal.appendChild(xmlDoc.createTextNode(emp.getEmp_Sal()));

innnerElement.appendChild(node_Empid);
innnerElement.appendChild(node_EmpName);
innnerElement.appendChild(node_EmpSal);

topElement.appendChild(innnerElement);

}
public String toString()
{
return this.getClass().getName();
}

public static void main(String args[])
{
XMLCreator a = new XMLCreator();
//StreamResult result = new StreamResult(System.out);
//System.out.println("Out put"+a.getData().toString());
try
{
Document doc = a.getData();

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);

String xmlString = result.getWriter().toString();
System.out.println(xmlString);
}
catch(Exception e)
{
e.getMessage();
}


//System.out.println(doc.getElementsByTagName("Empid").);

}
}




class EmployeeBean
{
/**
* @return Returns the emp_ID.
*/
public String getEmp_ID() {
return emp_ID;
}
/**
* @param emp_ID The emp_ID to set.
*/
public void setEmp_ID(String emp_ID) {
this.emp_ID = emp_ID;
}
/**
* @return Returns the emp_Sal.
*/
public String getEmp_Sal() {
return emp_Sal;
}
/**
* @param emp_Sal The emp_Sal to set.
*/
public void setEmp_Sal(String emp_Sal) {
this.emp_Sal = emp_Sal;
}

String emp_ID;
/**
* @return Returns the emp_Name.
*/
public String getEmp_Name() {
return emp_Name;
}
/**
* @param emp_Name The emp_Name to set.
*/
public void setEmp_Name(String emp_Name) {
this.emp_Name = emp_Name;
}
String emp_Name;

String emp_Sal;
}

java Interface Example

Do reports

Java Abstract Class Example

Base Class :
=============

package pkg_abstract;

import java.awt.Frame;
public class BaseWindow extends Frame {
}
Derived Class :
=============

package pkg_abstract;

public class EDSWindow extends BaseWindow{
public static void main(String args[])
{
EDSWindow a = new EDSWindow();
a.show();
}
}

Filter Pattern

package com.filter;

import java.util.Iterator;
import java.util.Vector;

public class FilterChain {
// filter chain
private Vector myFilters = new Vector();

// Creates new FilterChain
public FilterChain() {
// plug-in default filter services for example
// only. This would typically be done in the
// FilterManager, but is done here for example
// purposes
addFilter(new DebugFilter());
addFilter(new LoginFilter());
addFilter(new AuditFilter());
}

public void processFilter(
javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
throws javax.servlet.ServletException,
java.io.IOException {
Filter filter;

// apply filters
Iterator filters = myFilters.iterator();
while (filters.hasNext())
{
filter = (Filter)filters.next();
// pass request & response through various
// filters
filter.execute(request, response);
}
}

public void addFilter(Filter filter) {
myFilters.add(filter);
}
}

===============================================================
/*
* Created on Oct 13, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.filter;


/**
* @author tzg136
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class FilterManager {
public void processFilter(Filter target,
javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
throws javax.servlet.ServletException,
java.io.IOException {
FilterChain filterChain = new FilterChain();

// The filter manager builds the filter chain here
// if necessary

// Pipe request through Filter Chain
filterChain.processFilter(request, response);

//process target resource
target.execute(request, response);

}
}

Value List Handler

Client - Displays the result
=============================
package com.ValueList.client;

import com.ValueList.controller.EmpController;


public class EmpClient {
public void result()
{
EmpController e = new EmpController();
e.getAllEmpInfo();
}

public static void main(String args[])
{
EmpClient e = new EmpClient();
e.result();
}

}
===============================================
Controller :
===============================================
Client Calls controller :

package com.ValueList.controller;

import com.ValueList.common.ValueListHandler;
import com.ValueList.model.EmpDBManager;

public class EmpController {

public void getAllEmpInfo()
{
EmpDBManager objEmpDBManager = new EmpDBManager();
ValueListHandler allempInfo = objEmpDBManager.empInfo();
Object empbean = allempInfo.getCurrentElement();
System.out.println("CURRENT ELEMENT ");
System.out.println("CURRENT ELEMENT "+allempInfo.getCurrentElement());
System.out.println("SIZE "+allempInfo.getSize());
System.out.println("HAS NEXT "+allempInfo.hasNext());
}
}
============================
package com.ValueList.common;

// Import List class
import java.util.List;

public interface ValueListHandler {
public void setList(List list);
public int getSize();
public boolean hasNext();
public Object nextElement() ;
public Object getCurrentElement();
public void resetIndex() ;
}
====================================
Employee Value List Handler:
===================================
package com.ValueList.handler;

// Import List class
import java.util.List;

import com.ValueList.common.ValueListHandler;

/**
* This class holds the list of orders. The presentation layer uses the
* methods from this class to display the Order information.
* This class implements the ValueListHandler interface, which provides the
* necessary methods to iterate through the list.
*/
public class EmployeeHandler implements ValueListHandler {

private List ordersList = null;
private int listIndex = -1;
private int allRecordsSize = -1;

/**
* Sets the Orders list
* @param list - Order List
*/
public void setList(List list) {
ordersList = list;
}

/**
* Returns the size of the list
* @return - Size
*/
public int getSize() {
return ordersList.size();
}

/**
* Returns true if there are more elements in the list
* @return - true/false
*/
public boolean hasNext() {
return ( (listIndex+1) < ordersList.size() && ordersList.size() > 0 ) ;
}

/**
* Returns the next element in the list
* @return Next element
*/
public Object nextElement() {
return ordersList.get(++listIndex) ;
}

/**
* Returns the current element in the list
* @return Current element
*/
public Object getCurrentElement() {
if ( listIndex < 0 || ordersList.size() < 1 ) {
return null;
}
return ordersList.get(listIndex) ;
}

/**
* Resets the index
*/
public void resetIndex() {
listIndex = -1;
}
}
=========================================================
/*
* Created on Oct 5, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.ValueList.model;

import java.util.ArrayList;

import com.ValueList.bean.EmployeeBean;
import com.ValueList.common.ValueListHandler;
import com.ValueList.handler.EmployeeHandler;

/**
* @author tzg136
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class EmpDBManager {

EmployeeHandler empValueListHandler = new EmployeeHandler();
public ValueListHandler empInfo()
{

ArrayList orderList = new ArrayList();

EmployeeBean oEmployeeBean = new EmployeeBean();
oEmployeeBean.setEmp_ID("3939");
oEmployeeBean.setEmp_Name("ANDREW");
oEmployeeBean.setEmp_Sal("5.5LKS");

orderList.add(oEmployeeBean);

oEmployeeBean = new EmployeeBean();
oEmployeeBean.setEmp_ID("1 3939");
oEmployeeBean.setEmp_Name("1 ANDREW");
oEmployeeBean.setEmp_Sal("1 5.5LKS");

orderList.add(oEmployeeBean);

oEmployeeBean = new EmployeeBean();
oEmployeeBean.setEmp_ID("3 3939");
oEmployeeBean.setEmp_Name("3 ANDREW");
oEmployeeBean.setEmp_Sal("3 5.5LKS");

orderList.add(oEmployeeBean);


oEmployeeBean = new EmployeeBean();
oEmployeeBean.setEmp_ID("4 3939");
oEmployeeBean.setEmp_Name("4 ANDREW");
oEmployeeBean.setEmp_Sal("4 5.5LKS");

orderList.add(oEmployeeBean);



oEmployeeBean = new EmployeeBean();
oEmployeeBean.setEmp_ID("5 3939");
oEmployeeBean.setEmp_Name("5 ANDREW");
oEmployeeBean.setEmp_Sal("5 5.5LKS");

orderList.add(oEmployeeBean);


oEmployeeBean = new EmployeeBean();
oEmployeeBean.setEmp_ID("6 3939");
oEmployeeBean.setEmp_Name("6 ANDREW");
oEmployeeBean.setEmp_Sal("6 5.5LKS");

orderList.add(oEmployeeBean);


empValueListHandler.setList(orderList);

return empValueListHandler;
}

}
=======================================================

STRUTS - Iterator Example

update with MT CODE

Wednesday, March 4, 2009

PL SQL

SQL

EJB

Struts Dynaform example

JSP PAGE :
=========
<%@ taglib uri="struts/bean-el" prefix="bean" %>
<%@ taglib uri="struts/html-el" prefix="html" %>
<%@ taglib uri="struts/logic-el" prefix="logic" %>
<%@ taglib uri="jstl/c" prefix="c" %>
<html>
<head>
<link href="<html:rewrite page="/rr.css" />" rel="stylesheet" type="text/css">
<title><bean:message key="title.employee.employeeform"/></title>
</head>
<body>

<c:choose>
<c:when test="${employeeForm.map.methodToCall == 'insert'}">
<h1><bean:message key="title.employee.insert"/></h1>
</c:when>
<c:otherwise>
<h1><bean:message key="title.employee.update"/></h1>
</c:otherwise>
</c:choose>

<logic:messagesPresent>
<span id="errorsHeader"><bean:message key="errors.validation.header"/></span>
<html:messages id="error">
<li><c:out value="${error}"/></li>
</html:messages>
<hr>
</logic:messagesPresent>

<logic:messagesPresent message="true">
<html:messages id="message" message="true">
<span id="success"><c:out value="${message}"/></span><br>
</html:messages>
</logic:messagesPresent>

<html:form action="employeeAction" focus="name">
<table>
<tr>
<td >Name:</td>
<td><html:text property="name"/></td>
</tr>
<tr>
<td>Age:</td>
<td><html:text property="age"/></td>
</tr>

<tr>
<td>Department:</td>
<td>
<html:select name="employeeForm" property="department">
<html:options collection="departments" property="id" labelProperty="description"/>
</html:select>
</td>
</tr>
<tr>
<td>Favorite ice cream flavors:</td>
<td>
<c:forEach var="flavor" items="${flavors}">
<html:multibox name="employeeForm" property="flavorIDs">
<c:out value="${flavor.flavorID}"/>
</html:multibox>
<c:out value="${flavor.description}"/>
  
</c:forEach>
</td>
</tr>

</table>
<html:hidden name="employeeForm" property="methodToCall"/>

<c:choose>
<c:when test="${employeeForm.map.methodToCall == 'insert'}">
<html:submit><bean:message key="button.submit"/></html:submit>
</c:when>
<c:otherwise>
<html:submit><bean:message key="button.update"/></html:submit>
</c:otherwise>
</c:choose>

</html:form>

</body>
</html>

ACTION CLASS (DISPATCH):
=======================
package com.validate.action;

import org.apache.struts.action.*;
import org.apache.struts.actions.DispatchAction;
import org.apache.commons.beanutils.BeanUtils;

import com.validate.databasebean.EmployeeDTO;
import com.validate.handler.EmployeeService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public final class EmployeeDispatchAction extends DispatchAction {

public ActionForward insert(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
System.out.println("DISPATCHER INSERT ");
EmployeeService service = new EmployeeService();
DynaActionForm employeeForm = (DynaActionForm)form;
EmployeeDTO employeeDTO = new EmployeeDTO();
BeanUtils.copyProperties( employeeDTO, employeeForm );
service.insertEmployee( employeeDTO );
ActionMessages messages = new ActionMessages();
ActionMessage message = new ActionMessage("message.employee.insert.success");
messages.add( ActionMessages.GLOBAL_MESSAGE, message );
saveMessages( request, messages );
employeeForm.set("methodToCall","update");
return (mapping.findForward("insertSuccess"));
}

public ActionForward update(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
System.out.println("DISPATCHER Update");
EmployeeService service = new EmployeeService();
DynaActionForm employeeForm = (DynaActionForm)form;
EmployeeDTO employeeDTO = new EmployeeDTO();
BeanUtils.copyProperties( employeeDTO, employeeForm );
service.updateEmployee( employeeDTO );
ActionMessages messages = new ActionMessages();
ActionMessage message = new ActionMessage("message.employee.update.success");
messages.add( ActionMessages.GLOBAL_MESSAGE, message );
saveMessages( request, messages );
return (mapping.findForward("updateSuccess"));
}
}
=======================================================================
package com.validate.databasebean;
public class EmployeeDTO {
private String name;
private int age;
private int department;
private String[] flavorIDs;

public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setDepartment(int department) {
this.department = department;
}
public void setFlavorIDs(String[] flavorIDs) {
this.flavorIDs = flavorIDs;
}

public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getDepartment() {
return department;
}
public String[] getFlavorIDs() {
return flavorIDs;
}
}
======================================================

package com.validate.handler;

import java.util.ArrayList;
import java.util.Collection;

import com.validate.databasebean.DepartmentBean;
import com.validate.databasebean.EmployeeDTO;
import com.validate.databasebean.FlavorBean;


public class EmployeeService {
public EmployeeDTO insertEmployee( EmployeeDTO employee ) {
//in real life call other business classes to do insert
//ie:
//EmployeeDAO.insertEmployee( employee );
System.out.println("INSERT");
return employee;
}
public EmployeeDTO updateEmployee( EmployeeDTO employee ) {
//in real life call other business classes to do insert
//ie:
//EmployeeDAO.insertEmployee( employee );
System.out.println("UPDATE");
return employee;
}







}
====================================================

Hibernate Example

CREATE TABLE /*!32312 IF NOT EXISTS*/ `employee` (
`id` int(10) unsigned default NULL,
`empname` varchar(50) default NULL,
`date_of_joining` date default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
===================

hibernate.cfg.xml
===================
<?xml version="1.0" encoding="UTF-8"?>
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="myfactory">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/csr</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/csr/bean/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
============================
Employee.hbm.xml
============================
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.csr.bean">
<class name="Employee" >
<id name="id" column="id" type="integer">
<generator class="increment"></generator>
</id>
<property name="empname" column="employeename" type="string"/>
<property name="DOJ" column="date_of_joining" type="date"/>
</class>
</hibernate-mapping>

=============
package com.csr.bean;

import java.util.Date;

public class Employee {
private int id;
private String empname;
private Date DOJ;
public Date getDOJ() {
return DOJ;
}
public void setDOJ(Date doj) {
DOJ = doj;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}


}
===============
<%
SessionFactory factory=null;
Session ses=null;
Transaction trans=null;
try
{
String bookname = request.getParameter("bookname");
factory=new Configuration().configure().buildSessionFactory();
ses=factory.openSession();
trans=ses.beginTransaction();
Book book = new Book();
book.setLngBookId(4);
book.setStrBookName(bookname);
//ses.update(book);
ses.delete(book);
trans.commit();
ses.flush();
ses.close();
System.out.println("Book object persisted to the database.");
}
catch(Exception e)
{
out.println("error "+e.getMessage());
}
%>

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

ITIL

Monday, March 2, 2009

FUTURE PLAN

Do PHD in Computer Science