Sunday, November 7, 2010

load sub tables data without using hibernate lazy="false"

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.HibernateException;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class StudentDaoHibernateImpl extends HibernateDaoSupport implements StudentDao {

public Student getStudent(long studentId) thows StudentRetrieveException {
try {
//get hibernate session
Criteria crit = getSession().createCriteria(Student.class);
//join sub table
crit.setFetchMode("Subject", FetchMode.JOIN);
//filter student
crit.add(Restrictions.eq("studentId", studentId));
//create alias
crit.createAlias("Subject","sub");
//order by subject ID
crit.addOrder(Order.asc("sub.subjectId"));
//return result
return (Student) crit.uniqueResult();
} catch (HibernateException e) {
throw new StudentRetrieveException("Student Retrieve Problem",e);
}
}

}

Thursday, May 13, 2010

Simple Spring & Hibernate Example

Needed lib
==========

hibernate3.jar
antlr-2.7.6.jar
asm.jar
asm-attrs.jar
cglib-2.1.3.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
dom4j-1.6.1.jar
hibernate3.jar
jstl.jar
jta.jar
log4j-1.2.11.jar
mysql-connector-java-3.0.9-stable-bin.jar
spring.jar
standard.jar
spring.tld



1. Configure Web Xml

<?xml version="1.0" encoding="ISO-8859-1" ?>



<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">



<display-name>Test</display-name>

<description>Spring Base Application</description>



<context-param>

<param-name>contextConfigLocations</param-name>

<param-value>

/WEB-INF/applicationContext.xml

</param-value>

</context-param>



<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>



<servlet>

<servlet-name>spring</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

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

</servlet>



<servlet-mapping>

<servlet-name>spring</servlet-name>

<url-pattern>*.htm</url-pattern>

</servlet-mapping>





<welcome-file-list>

<welcome-file>

index.html

</welcome-file>

</welcome-file-list>



</web-app>







 



2.Configure Spring-Servlet XML

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

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">



<beans>



<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">

<property name="order" value="1"/>

</bean>



<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="configLocation" value="classpath:hibernate.cfg.xml" />

</bean>




<bean name="/userLogin.htm" class="web.controllers.UserLoginController">

<property name="managerService" ref="managerService"/>

</bean>





<bean id="saveUserValidator" class="web.validators.SaveUserValidator"/>





<bean id="addUserController" class="web.controllers.AddUserController">

<property name="sessionForm" value="false"/>

<property name="bindOnNewForm" value="false"/>

<property name="commandName" value="user"/>

<property name="commandClass" value="domain.User"/>

<property name="validator" ref="saveUserValidator"/>

<property name="formView" value="AddUser"/>

<property name="managerService" ref="managerService"/>

<property name="sessionFactory" ref="sessionFactory"/>

</bean>



<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">

<property name="basename" value="messages"/>

</bean>



<bean id="signonInterceptor" class="web.controllers.SignonInterceptor"/>





<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">

<property name="exceptionMappings">

<props>



<prop
key="org.springframework.dao.DataIntegrityViolationException">dberror</prop>

<prop key="org.hibernate.HibernateException">dberror</prop>

<prop key="java.lang.RuntimeException">dberror</prop>

<prop key="org.apache.jasper.JasperException">dberror</prop>

<prop key="javax.servlet.ServletException">dberror</prop>



</props>

</property>

</bean>



<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="order" value="2"/>



<property name="interceptors">

<list>

<ref bean="signonInterceptor"/>

</list>

</property>



<property name="mappings">

<props>





<prop key="/AddUser.htm">addUserController</prop>







</props>

</property>

</bean>



<bean id="viewResolver"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">

<property name="basename" value="views"/>

</bean>

</beans>

 



3.Configure AppicationContext XML


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

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">



<beans>



<!-- ========================= GENERAL DEFINITIONS ========================= -->



<!-- Transactional proxy for the primary business objects -->

<bean id="managerService" class="org.springframework.aop.framework.ProxyFactoryBean">

<property name="target">

<ref local="managerServiceTarget"/>

</property>

<property name="proxyTargetClass" value="false"/>

<property name="proxyInterfaces">

<list>

<value>service.ManagerService</value>

</list>

</property>

</bean>



<!-- DAO -->

<bean id="userDao" class="dao.hibernate.UserDaoHibernateImpl"/>





<!-- Business Objects -->

<bean id="managerServiceTarget" class="service.ManagerServiceImpl">



<property name="userDao" ref="userDao"/>





</bean>



















</beans>

 




4. Hibernate Configuration

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

<!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="dialect">org.hibernate.dialect.PostgreSQLDialect</property>

<property name="connection.datasource">java:PostgresDS</property>


 <!--<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>-->

<!--<property name="connection.url">jdbc:oracle:thin:@serverip:port:sid</property>-->

<!--<property name="connection.username">xxxx</property>-->

<!--<property name="connection.password">xxxx</property>-->




<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

<property name="hibernate.c3p0.max_size">20</property>

<property name="hibernate.c3p0.min_size">5</property>

<property name="hibernate.c3p0.timeout">300</property>

<property name="hibernate.c3p0.max_statements">50</property>

<property name="hibernate.c3p0.idle_test_period">3000</property>



<!-- print SQL to stdout -->

<property name="show_sql">false</property>

<property name="format_sql">false</property>





<mapping resource="domain/user.hbm.xml"/>





</session-factory>

</hibernate-configuration>





5.AddUser.jsp

<%@ taglib prefix="spring" uri="spring.tld" %>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>



<head><link rel="stylesheet" href="pop_style.css"></link>

<title>Welcome to Clinic Portal</title>



<style type="text/css">

</style>







<link href="eHosStoreStyles.css" rel="stylesheet" type="text/css">

</head>

<body onload="document.my.username.focus();" onkeydown="" leftmargin="0"
topmargin="0" rightmargin="0" bottommargin="0" class="optionsTop">



<table width="100%" height="0" border="0" style="border-collapse: collapse"
cellpadding="0" cellspacing="0">



<tr>

<td width="1%" height="30" align="left" background="Images/titleMiddle.gif"
class="titles">

<img src="Images/titleCorner.gif" width="30" height="30" border="0"></td>

<td valign="middle" background="Images/titleMiddle.gif" class="titles">

<p style="margin-right:10">

<strong><font face="Times New Roman, Times, serif" color="#000099">Add
User</font></strong></p></td>

</tr>





<br>

<form name="my" id="my" method="post" >

<table border="0" width="59%" height="100" align="center" class="bodyTable">

<tr>

<td height="10" valign="top"> <div align="center">

<spring:hasBindErrors name="user"><font color="red">

<b><fmt:message key="addUser.error.heading"/></b></font>

</spring:hasBindErrors>

<br>

</div>

</td>

</tr>

<tr>

<td class="rowgrey">

<spring:bind path="user.username">User Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
:</td>

<td width="477" align="left" class="rowgrey"><input size="40" type="text"
value="${status.value}" name="username" >

<font color="red">${status.errorMessage}</font>

</spring:bind>

</td>

</tr>

<tr>

<td class="rowgrey"><spring:bind path="user.firstName">First Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
:</td>

<td width="477" align="left" class="rowgrey"><input size="40" type="text"
value="${status.value}" name="firstName" >

<font color="red">${status.errorMessage}</font>

</spring:bind>

</td>

</tr>

<tr>

<td class="rowgrey"><spring:bind path="user.lastName">Last Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
:</td>

<td width="477" align="left" class="rowgrey"><input size="40" type="text"
value="${status.value}" name="lastName" >

<font color="red">${status.errorMessage}</font>

</spring:bind>

</td>

</tr>



<tr>

<td class="rowgrey"><spring:bind path="user.userpwd">Password&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
:</td><td width="477" align="left" class="rowgrey">

<input type="password" value="${status.value}" size="40" id="userpwd"
name="userpwd" >

<font color="red">${status.errorMessage}</font>

</spring:bind> </td>

</tr>

<tr>

<td class="rowgrey"><spring:bind path="user.userpwd">Confirm
Password&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
:</td><td width="477" align="left" class="rowgrey">

<input type="password" value="${status.value}" id="pwd" size="40" name="pwd" >

<font color="red">${status.errorMessage}</font>

</spring:bind> </td>

</tr>

<tr>

<td class="rowgrey"><spring:bind path="user.usertype"> User
Type&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; :</td>

<td width="477" align="left" class="rowgrey">

<select name="usertype" >

<option value="A">Administrator</option>

<option value="U">User</option>

</select>

<font color="red">${status.errorMessage}</font>

</spring:bind> </td>

</tr>







<tr>

<td
class="rowgrey">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</td>

<td width="477" align="left" class="rowgrey">

<input type="submit" id="submit" name="submit" class="buttons" value="Add User">

</td>

</tr>









</table>



</form>



<p><b>&nbsp;</b></p>







</body>



<script type="text/javascript" language="JavaScript1.2"
src="pop_events.js"></script>

</html>




6.Configure views.properties file

Home.class=org.springframework.web.servlet.view.JstlView
Home.url=/WEB-INF/jsp/home.jsp

AddUser.class=org.springframework.web.servlet.view.JstlView
AddUser.url=/WEB-INF/jsp/AddUser.jsp

7.configure messages.properties File

addUser.title=Add User page
addUser.error.heading=Please fix all the errors!
addUser.error.username.missing=The User Name field is missing
addUser.error.userpwd.missing=The password field is missing
addUser.error.usertype.missing=The Usertype is missing

8.DAO Class





package dao.hibernate;





import java.util.List;

import java.util.ArrayList;



import org.apache.log4j.Logger;

import org.apache.log4j.Level;

import org.hibernate.*;

import org.hibernate.criterion.Restrictions;

import org.hibernate.criterion.Expression;





import domain.User;

import dao.UserDao;





public class UserDaoHibernateImpl implements UserDao

{

public void saveUser(User user)throws HibernateException {

Session session = null;

Transaction tx = null;



try {

// Open a new session or get the current session

session = SessionProvider.currentSession();

// Begin the transaction

tx = session.beginTransaction();

session.saveOrUpdate(user);

//SessionProvider.closeSession();

// Commit the transaction

tx.commit();

SessionProvider.closeSession();

tx = null;



} catch( HibernateException e ) {

try{

tx.rollback();



} catch (HibernateException cannotRollback) {



// log this error

}



throw e;

//e.printStackTrace();



} finally {



// Close the session

if (session != null) SessionProvider.closeSession();



}





}





public void updateUser(User user1)throws HibernateException {

Session session = null;

Transaction tx = null;



try {

// Open a new session or get the current session

session = SessionProvider.currentSession();

// Begin the transaction

tx = session.beginTransaction();



User loaduser = (User) session.load(User.class, user1.getUserId(),
LockMode.UPGRADE);

loaduser.setUserId( user1.getUserId() );

loaduser.setStatus(user1.getStatus());

//loaduser.setUsername();

loaduser.setUserpwd(user1.getUserpwd());

loaduser.setUsertype(user1.getUsertype());

loaduser.setFirstName(user1.getFirstName());

loaduser.setLastName(user1.getLastName());

session.update(loaduser);

tx.commit();

SessionProvider.closeSession();



// Commit the transaction



tx = null;



} catch( HibernateException e ) {

try{

tx.rollback();



} catch (HibernateException cannotRollback) {



// log this error

}



throw e;

// e.printStackTrace();



} finally {



if (session != null) SessionProvider.closeSession();



}



}



public User getUser(String userName) throws HibernateException {

// Open a new session or get the current session

Session session = SessionProvider.currentSession();

User loaduser = new User();



try{

//loaduser = (user) session.get(user.class, userName);

Criteria crit = session.createCriteria(User.class);

crit.add(Restrictions.eq("username",userName));

crit.setMaxResults(1);

loaduser=(User) crit.uniqueResult();





} catch(HibernateException unexpected){



throw unexpected;



} finally{



if (session != null) SessionProvider.closeSession();

}



return loaduser;

}





public List getAllUser() throws HibernateException {

// Open a new session or get the current session

Session session = SessionProvider.currentSession();

List results =new ArrayList();



try{



Criteria crit = session.createCriteria(User.class);

results=crit.list();



} catch(HibernateException unexpected){

throw unexpected;



} finally{



if (session != null) SessionProvider.closeSession();

}



return results;



}



public void deleteUser(int jobid) throws HibernateException {



Session session = SessionProvider.currentSession();

try{

Transaction tx = session.beginTransaction();

User mm = loaduser(jobid);

session.delete( mm );

tx.commit();

}catch (Exception e){

e.printStackTrace();

}finally{

if (session != null) SessionProvider.closeSession();

}



}



public User loaduser( int id )throws HibernateException {

Session session = SessionProvider.currentSession();

User loaduser=new User();

try{

loaduser= (User) session.load(User.class, id );

}catch (Exception e){

e.printStackTrace();

}finally{

if (session != null) SessionProvider.closeSession();

}

return loaduser;

}



public List searchUser(String userName){

Session session = SessionProvider.currentSession();

List results = null;



try{



Criteria crit = session.createCriteria(User.class);

crit.add(Expression.like( "username","%"+userName.toUpperCase()+"%" ) );

results=crit.list();







} catch(HibernateException unexpected){

throw unexpected;



} finally{



if (session != null) SessionProvider.closeSession();

}



return results;



}



}



 



9. SessionProvider.class


package dao.hibernate;



import org.hibernate.cfg.Configuration;

import org.hibernate.SessionFactory;

import org.hibernate.Session;

import org.hibernate.FlushMode;

import org.hibernate.HibernateException;







public class SessionProvider

{

private static final SessionFactory sessionFactory;

public static final ThreadLocal session = new ThreadLocal();

private static int dbSessionCount;







static

{

try

{





sessionFactory = new
Configuration().configure("hibernate.cfg.xml").buildSessionFactory();



}

catch (HibernateException ex)

{

ex.printStackTrace();

throw new RuntimeException("Exception building SessionFactory: " +

ex.getMessage(), ex);

}

}





public static Session currentSession() throws HibernateException

{

Session s = (Session) session.get();

//System.out.println("--------------CurrentSession------------"+dbSessionCount);





if (s == null)

{

dbSessionCount++;

s = sessionFactory.openSession();



System.out.println("--------------OpenSession------------"+dbSessionCount);

s.setFlushMode(FlushMode.COMMIT);

session.set(s);





}

return s;

}



public static void closeSession() throws HibernateException

{

Session s = (Session) session.get();

session.set(null);



if (s != null)

{

dbSessionCount--;

s.close();



System.out.println("--------------ClosedSession------------"+dbSessionCount);



}

}

}



 



10.ManagerServiceImpl.java

/*

* JStockManager Project

*/

package service;



import java.util.List;

//

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

//

//



import dao.*;

import domain.*;





public class ManagerServiceImpl implements ManagerService {



private Log logger = LogFactory.getLog(this.getClass());







private UserDao userDao;







public void setUserDao(UserDao UserDao) {

this.userDao = UserDao;

}









// insert
-----------------------------------------------------------------------------------------------







public void saveUser(User user) throws Exception {

this.logger.info("entering method saveUser");



try {

userDao.saveUser(user);





} catch (Exception e) {

String msg = "Could not saveUser " + e.toString();

this.logger.error(msg, e);

throw e;



}

}







// update
-----------------------------------------------------------------------------------------------







public void updateUser(User user) throws Exception {

this.logger.info("entering method updateUser");



try {

this.userDao.updateUser(user);

} catch (Exception e) {

String msg = "Could not updateUser";

this.logger.error(msg, e);

throw e;



}

}





// delete
-----------------------------------------------------------------------------------------------







public void deleteUser(int userid) {

this.logger.info("entering method deleteUser");



try {

this.userDao.deleteUser(userid);

} catch (Exception e) {

String msg = "Could not deleteUser";

this.logger.error(msg, e);





}

}





// get
-----------------------------------------------------------------------------------------









public User getUser(String userName) {

this.logger.info("entering method getUser");

try {

return this.userDao.getUser(userName);

} catch (Exception e) {

String msg = "Could not getUser for id of " + userName;

this.logger.error(msg, e);

return null;



}

}







// get
all----------------------------------------------------------------------------------









public List getAllUser() {

this.logger.info("entering method getAllUser");

try {

return this.userDao.getAllUser();

} catch (Exception e) {

String msg = "Could not getAllUser products";

this.logger.error(msg, e);

return null;



}

}







//search-----------------------------------------------------------------------





public List searchUser(String userName){

this.logger.info("entering method searchUser");

try {

return this.userDao.searchUser(userName);

} catch (Exception e) {

String msg = "Could not searchSuplier products";

this.logger.error(msg, e);

return null;



}



}





//-----------------------------------------------------------



}





 



11.SaveUserValidator.java

package web.validators;



import org.springframework.validation.Errors;

import org.springframework.validation.Validator;

import domain.User;





public class SaveUserValidator implements Validator

{

public boolean supports(Class checkMe)

{

return checkMe.equals(User.class);

}



public void validate(Object object, Errors errors)

{

User user1 = (User) object;



if (user1 == null)

{

errors.rejectValue("user", "SaveUser.error.novalue",

"Value required.");

}



String name= "";

String pwd = "";

String type="";

String firstName="";

String lastName="";



if(user1!=null){

name= user1.getUsername();

pwd = user1.getUserpwd();

type=user1.getUserType();

firstName=user1.getFirstName();

lastName=user1.getLastName();

}







if ((name == null) || (name.length() < 1))

{

errors.rejectValue("username", "SaveUser.error.name.missing",

"name is missing.");

}

if ((firstName == null) || (firstName.length() < 1))

{

errors.rejectValue("firstName", "SaveUser.error.name.missing",

"first Name is missing.");

}

if ((lastName == null) || (lastName.length() < 1))

{

errors.rejectValue("lastName", "SaveUser.error.name.missing",

"last Name is missing.");

}

if ((pwd == null) || (pwd.length() < 1))

{

errors.rejectValue("userpwd", "SaveUser.error.name.missing",

"pwd is missing.");

}

if ((type== null) || (type.length() < 1))

{

errors.rejectValue("usertype", "SaveUser.error.name.missing",

"type is missing.");

}









}

}







 



12.AddUserController.java

package web.controllers;



import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.SimpleFormController;



import java.util.HashMap;

import java.util.Map;



import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;





import service.ManagerService;

import domain.User;





public class AddUserController extends SimpleFormController

{



private ManagerService ManagerService;

private String name;

private String ip;

private String serverMsg="";



public void setManagerService(ManagerService ManagerService) {

this.ManagerService = ManagerService;

}







public ModelAndView onSubmit(Object object) {

try{

User user1 = (User)object;

user1.setStatus(1);

user1.setUserpwd(user1.getUserpwd());



ManagerService.saveUser(user1);



}

catch(Exception e)

{



e.printStackTrace();

serverMsg=e.getCause().getMessage();

}



return new ModelAndView("Home");



}





protected Map referenceData(HttpServletRequest request)

throws ServletException

{

Map refData = new HashMap();

try{





UserSession user = (UserSession)
request.getSession(true).getAttribute("userSession");

name = user.getName();

ip = user.getIp();



}

catch(Exception e)

{

e.printStackTrace();

}

return refData;

}



}







 



13.SignonInterceptor.java

package web.controllers;



import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



import org.apache.log4j.Logger;

import org.apache.log4j.BasicConfigurator;



import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.ModelAndViewDefiningException;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import org.springframework.web.util.WebUtils;



public class SignonInterceptor extends HandlerInterceptorAdapter {



public boolean preHandle(HttpServletRequest request, HttpServletResponse
response, Object handler)

throws Exception {





UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");



if (userSession == null) {





request.setAttribute("exception","User has LogOut Please Login!");

response.sendRedirect("errorPage.jsp");

return false;

}

else {



return true;

}

}



}









 



14.UserLoginController.java





package web.controllers;



import domain.User;





import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



import org.apache.log4j.Logger;

import org.apache.log4j.Level;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.Controller;

import service.ManagerService;

import Utility.Constants;





public class UserLoginController

implements Controller {



private ManagerService ManagerService;

Logger logger;



public UserLoginController() {



}



public void setManagerService(ManagerService managerService) {

this.ManagerService = managerService;

logger = Logger.getLogger("web/controllers/UserLoginController");

logger.setLevel(Level.ALL);

}



public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {





String username = "gayan";

String password = "123";

String utype = "A";

int state = 0;

String name = "";

String place = "";

String type_ = "";

String dbPassword = "";

String ip = request.getRemoteAddr().trim();

System.out.println("---------------Attempt to login---------" + utype);

UserSession userSession = new UserSession();

userSession.setName(name);

userSession.setPlace(place);

userSession.setType_(type_);

userSession.setIp(ip);

userSession.setPwd(dbPassword);

request.getSession(true).setAttribute("userSession", userSession);

// ManagerService.getUser(username);

System.out.println("---------------Succesfull login---------" + utype);





return new ModelAndView("Home");

}



}











 




15.UserSession.java


package web.controllers;







public class UserSession {



private String name;

private String ip;

private String place; // user's place

private String type_; // to identify the what kind of user is trying to login

private String pwd;



public String getPwd() {

return pwd;

}



public void setPwd(String pwd) {

this.pwd = pwd;

}









public void setName(String name) {

this.name = name;

}



public void setIp(String ip) {

this.ip = ip;

}



public void setPlace(String place) {

this.place = place;

}



public void setType_(String type_) {

this.type_ = type_;

}





public UserSession() {



}



public String getName() {

return name;

}

public String getType_() {

return type_;

}

public String getPlace() {

return place;

}

public String getIp() {

return ip;

}





}













 



16.User.java



package domain;



import java.io.Serializable;



/**

* Category business object.

*

* @author <a href="mailto:gayand@ceit.pdn.ac.lk">Gayan Dissanayake</a>

*/

public class User implements Serializable {



private int userId;

private String username;

private String userpwd;

private int status;

private String usertype;

private String firstName;

private String lastName;



public String getFirstName() {

return firstName;

}



public void setFirstName(String firstName) {

this.firstName = firstName;

}



public String getLastName() {

return lastName;

}



public void setLastName(String lastName) {

this.lastName = lastName;

}







public int getUserId() {

return userId;

}



public void setUserId(int userId) {

this.userId = userId;

}







public String getUserpwd() {

return userpwd;

}



public void setUserpwd(String userpwd) {

this.userpwd = userpwd;

}







public int getStatus() {

return status;

}



public void setStatus(int status) {

this.status = status;

}







public String getUsertype() {

return usertype;

}



public void setUsertype(String usertype) {

this.usertype = usertype;

}





/**

* Default constructor.

*/

public User() {

}









public String getUserType() {

return this.usertype;

}



public void setUserType(String usertype) {

this.usertype = usertype;

}



public String getUsername() {

return this.username;

}



public void setUsername(String newUsername) {

this.username = newUsername;

}





}















 



17.user.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>

<class name="domain.User" table="user">

<id name="userId" column="userId" type="int">

<generator class="native"/>

</id>

<property name="username" column="username" type="java.lang.String"/>

<property name="userpwd" column="userpwd" type="java.lang.String"/>

<property name="status" column="status" type="int"/>

<property name="usertype" column="usertype" type="java.lang.String"/>

<property name="firstName" column="firstName" type="java.lang.String"/>

<property name="lastName" column="lastName" type="java.lang.String"/>

</class>

</hibernate-mapping>

















 



18.postgres-ds.xml


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



<!-- ===================================================================== -->

<!-- -->

<!-- JBoss Server Configuration -->

<!-- -->

<!-- ===================================================================== -->



<!-- $Id: postgres-ds.xml,v 1.3 2004/09/15 14:37:40 loubyansky Exp $ -->

<!-- ==================================================================== -->

<!-- Datasource config for Postgres -->

<!-- ==================================================================== -->





<datasources>

<local-tx-datasource>

<jndi-name>PostgresDS</jndi-name>

<connection-url>jdbc:postgresql://localhost/astro</connection-url>

<driver-class>org.postgresql.Driver</driver-class>

<user-name>postgres</user-name>

<password>mysql</password>

<!-- sql to call when connection is created

<new-connection-sql>some arbitrary sql</new-connection-sql>

-->



<!-- sql to call on an existing pooled connection when it is obtained from pool


<check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>

-->



<!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->

<metadata>

<type-mapping>PostgreSQL 7.2</type-mapping>

</metadata>

</local-tx-datasource>



<local-tx-datasource>

<jndi-name>PostgresDS1</jndi-name>

<connection-url>jdbc:postgresql://localhost/starfriends</connection-url>

<driver-class>org.postgresql.Driver</driver-class>

<user-name>postgres</user-name>

<password>mysql</password>

<!-- sql to call when connection is created

<new-connection-sql>some arbitrary sql</new-connection-sql>

-->



<!-- sql to call on an existing pooled connection when it is obtained from pool


<check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>

-->



<!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->

<metadata>

<type-mapping>PostgreSQL 7.2</type-mapping>

</metadata>

</local-tx-datasource>





</datasources>

Tuesday, February 2, 2010

Differance between hibernate session find() vs get(),load();

main difference is
get() and load() returns >>>>>>>>>> object
but find() returns >>>>>>>>> List

cascade Attribute in Hibernate .hbm.xml

The cascade="all" attribute is a very important one. It explains how Hibernate should act while manipulating connected objects. In our specific situation, when an Order is created, we definitely want all of its OrderItems to be created as well, and, of course, when an Order is deleted, we also want all of its OrderItems to be deleted. There are three more options cascade attribute can hold, none, save-update, and delete



1) cascade="none", the default, tells Hibernate to ignore the association.
2) cascade="save-update" tells Hibernate to navigate the association when the
transaction is committed and when an object is passed to save() or
update() and save newly instantiated transient instances and persist changes to
detached instances.
3) cascade="delete" tells Hibernate to navigate the association and delete persistent
instances when an object is passed to delete().
4) cascade="all" means to cascade both save-update and delete, as well as
calls to evict and lock.
5) cascade="all-delete-orphan" means the same as cascade="all" but, in addition,
Hibernate deletes any persistent entity instance that has been removed
(dereferenced) from the association (for example, from a collection).
6) cascade="delete-orphan" Hibernate will delete any persistent entity
instance that has been removed (dereferenced) from the association (for
example, from a collection).

Advantage of Hibernate session load() vs get()

If load() can’t find the object in the cache or database, an exception is
thrown.
The load() method never returns null.

The get() method returns
null if the object can’t be found.

The get() method will return a FULL initialized object if nothing is on the session cache, that means several DB hits depending on your mappings.

While the load() method will return a proxy (or the instance if already initialized), allowing lazy initialization and thus better performance

Choosing between get() and load() is easy: If you’re certain the persistent
object exists, and nonexistence would be considered exceptional, load() is a
good option. If you aren’t certain there is a persistent instance with the given
identifier, use get() and test the return value to see if it’s null.