custom paging with strut and hibernate


STEP : 1 Database Structure

— phpMyAdmin SQL Dump
— version 3.3.9
http://www.phpmyadmin.net

— Host: localhost
— Generation Time: Jun 16, 2011 at 06:39 PM
— Server version: 5.5.8
— PHP Version: 5.3.5

SET SQL_MODE=”NO_AUTO_VALUE_ON_ZERO”;


— Database: `college`

— ——————————————————–


— Table structure for table `courses`

CREATE TABLE IF NOT EXISTS `courses` (
`course_id` int(11) NOT NULL AUTO_INCREMENT,
`course_name` varchar(50) NOT NULL,
PRIMARY KEY (`course_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=67 ;


— Dumping data for table `courses`

INSERT INTO `courses` (`course_id`, `course_name`) VALUES
(1, ‘MnBBS’),
(2, ‘MBA’),
(3, ‘BSC’),
(14, ‘MBA’),
(13, ‘MnBBS’),
(12, ‘BSC’),
(11, ‘MBA’),
(10, ‘MnBBS’),
(15, ‘BSC’),
(16, ‘MnBBS’),
(17, ‘MBA’),
(18, ‘BSC’),
(19, ‘MnBBS’),
(20, ‘MBA’),
(21, ‘BSC’),
(22, ‘MnBBS’),
(23, ‘MBA’),
(24, ‘BSC’),
(25, ‘MBA’),
(26, ‘MnBBS’),
(27, ‘BSC’),
(28, ‘MBA’),
(29, ‘MnBBS’),
(30, ‘BSC’),
(31, ‘MnBBS’),
(32, ‘MBA’),
(33, ‘BSC’),
(34, ‘MnBBS’),
(35, ‘MBA’),
(36, ‘BSC’),
(37, ‘MnBBS’),
(38, ‘MBA’),
(39, ‘BSC’),
(40, ‘MBA’),
(41, ‘MnBBS’),
(42, ‘BSC’),
(43, ‘MBA’),
(44, ‘MnBBS’),
(45, ‘BSC’),
(46, ‘MnBBS’),
(47, ‘MBA’),
(48, ‘BSC’),
(49, ‘MnBBS’),
(50, ‘MBA’),
(51, ‘BSC’),
(52, ‘MnBBS’),
(53, ‘MBA’),
(54, ‘BSC’),
(55, ‘MBA’),
(56, ‘MnBBS’),
(57, ‘BSC’),
(58, ‘MBA’),
(59, ‘MnBBS’),
(60, ‘BSC’),
(61, ‘MnBBS’),
(62, ‘MBA’),
(63, ‘BSC’),
(64, ‘MnBBS’),
(65, ‘MBA’),
(66, ‘BSC’);

STEP : 2 customPaging.java

package customPaging;

public class customPaging {

public String getpaging(String url,String form_name,int total_records, int current_page_no,int current_page_size)
{

String left_arrow=””;
String textbox=””;
String right_arrow=””;
String page_status=””;
String dropdown=””;
String output=””;
int total_pages;
int lower_record_limit;
int upper_record_limit;
String selected_page_size;

total_pages=(int)(total_records/current_page_size);
if((total_records%current_page_size)>0)
total_pages=total_pages+1;

System.out.println(“Total Records = “+total_records+” Page Size =”+ current_page_size+ ” Total Pages :”+(total_records%current_page_size));
if(current_page_no==1)
{
lower_record_limit=0;
upper_record_limit=current_page_no*current_page_size;
}
else
{
lower_record_limit=(current_page_no-1)*current_page_size;
upper_record_limit=current_page_no*current_page_size;
}

if(current_page_no==1)
left_arrow=”<img src=’page_images/left_arrow.png’ />”;
else
left_arrow=”<a href=’javascript:void(0);’ onclick=’submit_paging(“+(current_page_no-1)+”);’><img src=’page_images/left_arrow.png’ /></a>”;

if(current_page_no==total_pages || total_records <= current_page_size )
right_arrow=”<img src=’page_images/right_arrow.png’ />”;
else
right_arrow=”<a href=’javascript:void(0);’ onclick=’submit_paging(“+(current_page_no+1)+”);’><img src=’page_images/right_arrow.png’ /></a>”;

textbox=”<input type=’text’ name=’txt_current_page’ id=’txt_current_page’ value='”+current_page_no+”‘ style=’width:30px;text-align:center;’  onchange=’submit_textbox_paging(“+(current_page_no+1)+”);’      />”;

page_status=” “+(lower_record_limit+1)+” – “+upper_record_limit+” of “+total_records;
dropdown=”<select name=’current_page_size’ style=’width:50px;text-align:center;’ onChange=’select_paging();’>”;

for(int i=10;i<=100;i=i+10)
{
selected_page_size=””;
if(i==current_page_size)
selected_page_size=”selected=’selected'”;
dropdown=dropdown+”<option value='”+i+”‘ “+selected_page_size+”>”+i+”</option>”;
}

dropdown=dropdown+”</select>”;

output=”<div>”+left_arrow+”&nbsp;”+textbox+”&nbsp;”+right_arrow+”&nbsp;|&nbsp;”+page_status+”&nbsp;|&nbsp; Total Pages : “+total_pages+”&nbsp;|&nbsp; Page Size : “+dropdown+”</div>”;

output=output+”<input type=’hidden’ id=’current_page’ name=’current_page’ value='”+current_page_no+”‘ />”;

output=output+”<script type=’text/javascript’>”;
output=output+”function submit_paging(current_page_no)”;
output=output+”{“;
output=output+”    document.getElementById(‘current_page’).value=current_page_no; “;
output=output+” document.”+form_name+”.submit(); “;

output=output+”}”;
output=output+”function select_paging()”;
output=output+”{“;
// output=output+” document.getElementById(‘current_page’).value=current_page_no; “;
output=output+” document.”+form_name+”.submit(); “;
output=output+”}”;

output=output+”function submit_textbox_paging()”;
output=output+”{“;
output=output+” document.getElementById(‘current_page’).value=document.getElementById(‘txt_current_page’).value; “;
output=output+” document.”+form_name+”.submit(); “;
output=output+”}”;

output=output+” </script>”;

return output;
}

}

STEP :3 SearchcourseAction.java

/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package courses;

import java.util.List;

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import MyHibernet.HibernateSessionFactory;
import courses.SearchcourseForm;
import courses.Courses;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import customPaging.customPaging;

/**
* MyEclipse Struts
* Creation date: 06-07-2011
*
* XDoclet definition:
* @struts.action path=”/searchcourse” name=”searchcourseForm” input=”searchcourse.jsp” scope=”request” validate=”true”
* @struts.action-forward name=”sucess” path=”searchresult.jsp”
* @struts.action-forward name=”fail” path=”searchcourse.jsp”
*/
public class SearchcourseAction extends DispatchAction  {
/*
* Generated Methods
*/

private String search_result_paging=””;

/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward search(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
SearchcourseForm searchcourseForm = (SearchcourseForm) form;// TODO Auto-generated method stub
System.out.println(“called”);

int current_page_no=(request.getParameter(“current_page”)!=null)? Integer.parseInt(request.getParameter(“current_page”)):1 ;
int current_page_size=(request.getParameter(“current_page_size”)!=null)? Integer.parseInt(request.getParameter(“current_page_size”)):2;

System.out.println(“Current Page No :”+current_page_no+” Current Page Size :”+current_page_size);

String keyword=searchcourseForm.getKeyword();
List courses=getSearchResult(keyword,current_page_no,current_page_size);
request.setAttribute(“searchresult”, courses);
request.setAttribute(“keyword”, keyword);
request.setAttribute(“search_result_paging”, search_result_paging);

return mapping.findForward(“sucess”);
}

public List getSearchResult(String keyword,int current_page_no,int current_page_size)
{

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

Transaction transaction = null;
List courses =null;
String SqlStr=””;

//String SqlStr=”select courses.courseId,courses.courseName,count(students.name) as no_of_students from Courses as courses ,Students as students where students.courseId=courses.courseId and courses.courseName like ‘%”+keyword+”%’ group by courses.courseName order by courses.courseId”;

//START : Paging
transaction = session.beginTransaction();
SqlStr=”select courses.courseId,courses.courseName,courses.courseId as no_of_students from Courses as courses”;
courses = session.createQuery(SqlStr).list();
transaction.commit();
int total_records=courses.size();
int records_start=(current_page_size*(current_page_no-1));
System.out.println(“Total Rerocds=”+total_records+” Current Page No=”+current_page_no+” Current Page Size=”+current_page_size+ ” Records Start=”+records_start);
customPaging obj_paging=new customPaging();
search_result_paging=obj_paging.getpaging(“”, “searchcourseForm”,total_records,current_page_no,current_page_size);
//END : Paging

transaction = session.beginTransaction();
SqlStr=”select courses.courseId,courses.courseName,courses.courseId as no_of_students from Courses as courses”;//limit “+records_start+”,”+current_page_size;
System.out.println(SqlStr);

Query query= session.createQuery(SqlStr);
query.setFirstResult(records_start);
query.setMaxResults(current_page_size);
courses = query.list();
transaction.commit();

session.close();
return courses;
}

}

STEP:4 searchresult.jsp

<%@ page language=”java” pageEncoding=”UTF-8″%>
<%@ taglib uri=”http://struts.apache.org/tags-bean&#8221; prefix=”bean”%>
<%@ taglib uri=”http://struts.apache.org/tags-html&#8221; prefix=”html”%>
<%@page language=”java” import=”java.util.*”%>

<html>
<head>
<title>JSP for SearchcourseForm form</title>

<script type=”text/javascript”>
function checkuncheck(field)
{
var checkall=document.searchcourseForm.chkall;
if(checkall.checked==true)
checkAll(field);
else
uncheckAll(field);
}
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}

function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
function doOper(studentsid,method)
{

var answer = confirm(“Do you really want to delete this record ?”);
if (answer){
document.getElementById(“coursesid”).value=studentsid;
document.getElementById(“method”).value=method;
document.forms[“searchcourseForm”].submit();
return true;
}
else{
return false;
}

}
function doMultiOper(param,field,method)
{
if(param!=-1)
{
var counter=0;
for (i = 0; i < field.length; i++)
{
if(field[i].checked == true)
{
counter=1
break;
}
}
if(counter==1)
{
var answer = confirm(“Do you really want to delete this record ?”);
if (answer){

document.getElementById(“method”).value=method;
document.forms[“searchcourseForm”].submit();
return true;
}
else
{
return false;
}
}
else
{
alert(“Please select records atleat one!”);
return false;
}
}
}
</script>
</head>
<body>
<html:form action=”searchcourse.do”>

<table width=”700px”>
<tr>
<td width=”5%”>&nbsp;</td><td width=”20%”>&nbsp;</td><td width=”20%”>&nbsp;</td><td width=”20%”>Action :</td>
<td width=”35%”>
<select name=”oper” id=”oper” onchange=”doMultiOper(this.value,document.searchcourseForm.chk,’multidelete’);”>
<option value=”-1″>Select</option>
<option value=”delete”>Delete</option>
</select>

</td>
</tr>
<tr><td width=”5%”><input type=”checkbox” name=”chkall” onClick=”checkuncheck(document.searchcourseForm.chk)” /></td><td width=”20%”>Course Id</td><td width=”20%”>Course</td><td width=”20%”>Student</td><td width=”35%”>Action</td></tr>
<%
List searchresult = (List) request.getAttribute(“searchresult”);
%>
<%
for(Iterator itr=searchresult.iterator(); itr.hasNext(); )
{
Object[] obj_list =(Object[])itr.next();
%>

<tr>
<td><input type=”checkbox” name=”chk” value=”<%=obj_list[0] %>” /></td>

<td><%=obj_list[0] %></td>
<td><%=obj_list[1] %></td>
<td><%=obj_list[2] %></td>
<td>
<a href=”javascript:void(0);”  onClick=window.open(“editcourse.do?coursesid=<%=obj_list[0] %>&method=edit”,”Course”,”width=550,height=170,0,status=0,”);  >Edit</a>&nbsp;|&nbsp;
<a href=”javascript:void(0);” onclick=”doOper(‘<%=obj_list[0] %>’,’delete’);” >Delete</a>
</td>
</tr>

<%
}
%>
<tr>
<td colspan=”5″><%=request.getAttribute(“search_result_paging”) %></td>
</tr>
</table>
<html:hidden property=”keyword” styleId=”keyword” value=”<%=(String)request.getAttribute(“keyword”) %>” />
<html:hidden property=”method” styleId=”method” value=”search” />
<input type=”hidden” name=”coursesid” id=”coursesid” value=”” />

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

STEP 6: searchcourse.jsp

<%@ page language=”java” pageEncoding=”UTF-8″%>
<%@ taglib uri=”http://struts.apache.org/tags-bean&#8221; prefix=”bean”%>
<%@ taglib uri=”http://struts.apache.org/tags-html&#8221; prefix=”html”%>

<html>
<head>
<title>JSP for SearchcourseForm form</title>
</head>
<body>
<html:form action=”/searchcourse”>
keyword : <html:text property=”keyword”/><html:errors property=”keyword”/><br/>

<html:submit property=”method”>search</html:submit><br/>
<a href=”addcourse.jsp” >Add Course</a>

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

complete strut hibernate integration example ( with add,update,delete,multi delete in database)


STEP 1: DATABASE STRUCTURE

— phpMyAdmin SQL Dump
— version 3.3.9
http://www.phpmyadmin.net

— Host: localhost
— Generation Time: Jun 13, 2011 at 07:39 PM
— Server version: 5.5.8
— PHP Version: 5.3.5

SET SQL_MODE=”NO_AUTO_VALUE_ON_ZERO”;


— Database: `college`

— ——————————————————–


— Table structure for table `courses`

CREATE TABLE IF NOT EXISTS `courses` (
`course_id` int(11) NOT NULL AUTO_INCREMENT,
`course_name` varchar(50) NOT NULL,
PRIMARY KEY (`course_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;


— Dumping data for table `courses`

INSERT INTO `courses` (`course_id`, `course_name`) VALUES
(1, ‘MnBBS’),
(2, ‘MBA’),
(3, ‘BSC’);

— ——————————————————–


— Table structure for table `students`

CREATE TABLE IF NOT EXISTS `students` (
`studentsid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`course_id` int(11) NOT NULL,
PRIMARY KEY (`studentsid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=22 ;


— Dumping data for table `students`

INSERT INTO `students` (`studentsid`, `name`, `course_id`) VALUES
(11, ‘Andrew’, 1),
(4, ‘Jessica’, 3),
(5, ‘Kalley’, 4),
(18, ‘Andrew’, 1),
(15, ‘Rose’, 3);

————————————————————————————————-

STEP 2: Courses.java

package courses;

import org.apache.struts.action.ActionForm;

/**
* Courses entity. @author MyEclipse Persistence Tools
*/

public class Courses extends ActionForm implements java.io.Serializable {

// Fields

private Integer courseId;
private String courseName;

// Constructors

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

/** full constructor */
public Courses(String courseName) {
this.courseName = courseName;
}

// Property accessors

public Integer getCourseId() {
return this.courseId;
}

public void setCourseId(Integer courseId) {
this.courseId = courseId;
}

public String getCourseName() {
return this.courseName;
}

public void setCourseName(String courseName) {
this.courseName = courseName;
}

}

————————————————————————————————–

STEP 3:        SearchcourseAction.java

/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package courses;

import java.util.List;

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import MyHibernet.HibernateSessionFactory;
import courses.SearchcourseForm;
import courses.Courses;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
* MyEclipse Struts
* Creation date: 06-07-2011
*
* XDoclet definition:
* @struts.action path=”/searchcourse” name=”searchcourseForm” input=”searchcourse.jsp” scope=”request” validate=”true”
* @struts.action-forward name=”sucess” path=”searchresult.jsp”
* @struts.action-forward name=”fail” path=”searchcourse.jsp”
*/
public class SearchcourseAction extends DispatchAction  {
/*
* Generated Methods
*/

/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward search(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
SearchcourseForm searchcourseForm = (SearchcourseForm) form;// TODO Auto-generated method stub

String keyword=searchcourseForm.getKeyword();
List courses=getSearchResult(keyword);
request.setAttribute(“searchresult”, courses);
request.setAttribute(“keyword”, keyword);
return mapping.findForward(“sucess”);
}

public ActionForward multidelete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
SearchcourseForm searchcourseForm = (SearchcourseForm) form;// TODO Auto-generated method stub

String keyword=searchcourseForm.getKeyword();
String coursesid=(String)request.getParameter(“coursesid”);

String temp_courses_id[]=request.getParameterValues(“chk”);
String selected_students_id=””;
for(int i=0;i<temp_courses_id.length;i++)
{
selected_students_id=selected_students_id+temp_courses_id[i]+”,”;
}
selected_students_id=selected_students_id.substring(0,selected_students_id.length()-1);

Session sess = null;
try
{
SessionFactory fact = new Configuration().configure().buildSessionFactory();
sess = fact.openSession();
String hql = “delete from Courses courses where courseId in( “+selected_students_id +”)”;
Query query = sess.createQuery(hql);
int row = query.executeUpdate();
if (row == 0)
{
System.out.println(“Doesn’t deleted any row!”);
}
else
{
System.out.println(“Deleted    Row: ” + row);
}
sess.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}

List courses=getSearchResult(keyword);
request.setAttribute(“searchresult”, courses);
request.setAttribute(“keyword”, keyword);

return mapping.findForward(“sucess”);
}

public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
SearchcourseForm searchcourseForm = (SearchcourseForm) form;// TODO Auto-generated method stub

String keyword=searchcourseForm.getKeyword();
String coursesid=(String)request.getParameter(“coursesid”);

Session sess = null;
try
{
SessionFactory fact = new Configuration().configure().buildSessionFactory();
sess = fact.openSession();

String hql = “delete from Courses courses where courseId = “+coursesid;
Query query = sess.createQuery(hql);
int row = query.executeUpdate();
if (row == 0)
{
System.out.println(“Doesn’t deleted any row!”);
}
else
{
System.out.println(“Deleted    Row: ” + row);
}
sess.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}

List courses=getSearchResult(keyword);
request.setAttribute(“searchresult”, courses);
request.setAttribute(“keyword”, keyword);

return mapping.findForward(“sucess”);

}
public List getSearchResult(String keyword)
{

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

Transaction transaction = null;

transaction = session.beginTransaction();
String SqlStr=”select courses.courseId,courses.courseName,count(students.name) as no_of_students from Courses as courses ,Students as students where students.courseId=courses.courseId and courses.courseName like ‘%”+keyword+”%’ group by courses.courseName order by courses.courseId”;
System.out.println(SqlStr);
List courses = session.createQuery(SqlStr).list();

transaction.commit();
session.close();
return courses;
}
public ActionForward edit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
{

String coursesid=request.getParameter(“coursesid”);
System.out.println(“Edit call” +coursesid);

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

Transaction transaction = null;

transaction = session.beginTransaction();
String SqlStr=”select courses.courseId,courses.courseName from Courses as courses where courses.courseId ='”+coursesid+”‘”;
System.out.println(SqlStr);
List courses = session.createQuery(SqlStr).list();
System.out.println(“size=”+courses.size());
transaction.commit();
session.close();

request.setAttribute(“coursedata”, courses);
return mapping.findForward(“editcourse”);
}
public ActionForward update(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
{
Integer coursesid=Integer.parseInt(request.getParameter(“coursesid”));
String courseName=request.getParameter(“courseName”);
Session session = HibernateSessionFactory.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Courses course = (Courses) session.get(Courses.class, coursesid);
course.setCourseName(courseName);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return mapping.findForward(“searchpage”);
}
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
{

String courseName=request.getParameter(“courseName”);
Session session = HibernateSessionFactory.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Courses course = new Courses();
course.setCourseName(courseName);
session.save(course);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return mapping.findForward(“searchpage”);
}

}———————————————————————————–

STEP : 4 SearchcourseForm.java

/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package courses;

import org.apache.struts.action.ActionForm;

/**
* MyEclipse Struts
* Creation date: 06-07-2011
*
* XDoclet definition:
* @struts.form name=”searchcourseForm”
*/
public class SearchcourseForm extends ActionForm {
/*
* Generated fields
*/

/** keyword property */
private String keyword;

/*
* Generated Methods
*/

/**
* Returns the keyword.
* @return String
*/
public String getKeyword() {
return keyword;
}

/**
* Set the keyword.
* @param keyword The keyword to set
*/
public void setKeyword(String keyword) {
this.keyword = keyword;
}
}——————————————————————————-

STEP : 5 Courses.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”&gt;
<!–
Mapping file autogenerated by MyEclipse Persistence Tools
–>
<hibernate-mapping>
<class name=”courses.Courses” table=”courses” catalog=”college”>
<id name=”courseId” type=”java.lang.Integer”>
<column name=”course_id” />
<generator />
</id>
<property name=”courseName” type=”java.lang.String”>
<column name=”course_name” length=”50″ not-null=”true” />
</property>
</class>
</hibernate-mapping>

——————————————————————————–

STEP : 6 HibernateSessionFactory.java

package MyHibernet;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution.  Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {

/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = “/hibernate.cfg.xml”;
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private  static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;

static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println(“%%%% Error Creating SessionFactory %%%%”);
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}

/**
* Returns the ThreadLocal Session instance.  Lazy initialize
* the <code>SessionFactory</code> if needed.
*
*  @return Session
*  @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();

if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}

return session;
}

/**
*  Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println(“%%%% Error Creating SessionFactory %%%%”);
e.printStackTrace();
}
}

/**
*  Close the single hibernate session instance.
*
*  @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);

if (session != null) {
session.close();
}
}

/**
*  return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}

/**
*  return session factory
*
*    session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}

/**
*  return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}

}

—————————————————————————–

STEP : 7 Students.java

package students;

import courses.Courses;

/**
* Students entity. @author MyEclipse Persistence Tools
*/

public class Students implements java.io.Serializable {

// Fields

private Integer studentsid;
private String name;
private Integer courseId;

// Constructors

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

/** full constructor */
public Students(String name, Integer courseId) {
this.name = name;
this.courseId = courseId;
}

// Property accessors

public Integer getStudentsid() {
return this.studentsid;
}

public void setStudentsid(Integer studentsid) {
this.studentsid = studentsid;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public Integer getCourseId() {
return this.courseId;
}

public void setCourseId(Integer courseId) {
this.courseId = courseId;
}

}——————————————————————————————–

STEP :8 Students.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”&gt;
<!–
Mapping file autogenerated by MyEclipse Persistence Tools
–>
<hibernate-mapping>
<class name=”students.Students” table=”students” catalog=”college”>
<id name=”studentsid” type=”java.lang.Integer”>
<column name=”studentsid” />
<generator />
</id>
<property name=”name” type=”java.lang.String”>
<column name=”name” length=”50″ not-null=”true” />
</property>
<property name=”courseId” type=”java.lang.Integer”>
<column name=”course_id” not-null=”true” />
</property>
<!– <many-to-one name=”courseId” column=”course_id”/>  –>
</class>
</hibernate-mapping>

————————————————————————————————–

STEP : 9 hibernate.cfg.xml

<?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”&gt;

<!– Generated by MyEclipse Hibernate Tools.                   –>
<hibernate-configuration>

<session-factory>
<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>
<property name=”connection.url”>jdbc:mysql://localhost/college</property>
<property name=”connection.username”>root</property>
<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”myeclipse.connection.profile”>cmdriver</property>
<mapping resource=”courses/Courses.hbm.xml”/>
<mapping resource=”students/Students.hbm.xml”/>

</session-factory>

</hibernate-configuration>

——————————————————————————————————-

STEP : 10 addcourse.jsp

<%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%>
<%@ taglib uri=”http://struts.apache.org/tags-bean&#8221; prefix=”bean”%>
<%@ taglib uri=”http://struts.apache.org/tags-html&#8221; prefix=”html”%>

<%@page language=”java” import=”java.util.*”%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”;
%>

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<base href=”<%=basePath%>”>

<title>My JSP ‘editcourse.jsp’ starting page</title>

<meta http-equiv=”pragma” content=”no-cache”>
<meta http-equiv=”cache-control” content=”no-cache”>
<meta http-equiv=”expires” content=”0″>
<meta http-equiv=”keywords” content=”keyword1,keyword2,keyword3″>
<meta http-equiv=”description” content=”This is my page”>
<!–
<link rel=”stylesheet” type=”text/css” href=”styles.css”>
–>

</head>

<body>

<html:form action=”/addcourse”>
keyword : <html:text   property=”courseName” value=””/><br/>

<html:submit property=”method”>save</html:submit>

</html:form>

</body>
</html>
—————————————————————————————–

STEP : 11 editcourse.jsp

<%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%>
<%@ taglib uri=”http://struts.apache.org/tags-bean&#8221; prefix=”bean”%>
<%@ taglib uri=”http://struts.apache.org/tags-html&#8221; prefix=”html”%>

<%@page language=”java” import=”java.util.*”%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”;
%>

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<base href=”<%=basePath%>”>

<title>My JSP ‘editcourse.jsp’ starting page</title>

<meta http-equiv=”pragma” content=”no-cache”>
<meta http-equiv=”cache-control” content=”no-cache”>
<meta http-equiv=”expires” content=”0″>
<meta http-equiv=”keywords” content=”keyword1,keyword2,keyword3″>
<meta http-equiv=”description” content=”This is my page”>
<!–
<link rel=”stylesheet” type=”text/css” href=”styles.css”>
–>

</head>

<body>
<%
List searchresult = (List) request.getAttribute(“coursedata”);
%>
<%
for(Iterator itr=searchresult.iterator(); itr.hasNext(); )
{
Object[] obj_list =(Object[])itr.next();
%>
<html:form action=”/editcourse”>
keyword : <html:text   property=”courseName” value=”<%=obj_list[1].toString() %>”/><br/>

<input type=”hidden” name=”coursesid” id=”coursesid” value=”<%=obj_list[0] %>” />
<html:submit property=”method”>update</html:submit>

</html:form>
<%
}
%>

</body>
</html>

————————————————————————————————–

STEP : 12 searchcourse.jsp

<%@ page language=”java” pageEncoding=”UTF-8″%>
<%@ taglib uri=”http://struts.apache.org/tags-bean&#8221; prefix=”bean”%>
<%@ taglib uri=”http://struts.apache.org/tags-html&#8221; prefix=”html”%>

<html>
<head>
<title>JSP for SearchcourseForm form</title>
</head>
<body>
<html:form action=”/searchcourse”>
keyword : <html:text property=”keyword”/><html:errors property=”keyword”/><br/>

<html:submit property=”method”>search</html:submit><br/>
<a href=”addcourse.jsp” >Add Course</a>

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

———————————————————————————————-

STEP : 13 searchresult.jsp

<%@ page language=”java” pageEncoding=”UTF-8″%>
<%@ taglib uri=”http://struts.apache.org/tags-bean&#8221; prefix=”bean”%>
<%@ taglib uri=”http://struts.apache.org/tags-html&#8221; prefix=”html”%>
<%@page language=”java” import=”java.util.*”%>

<html>
<head>
<title>JSP for SearchcourseForm form</title>

<script type=”text/javascript”>
function checkuncheck(field)
{
var checkall=document.searchcourseForm.chkall;
if(checkall.checked==true)
checkAll(field);
else
uncheckAll(field);
}
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}

function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
function doOper(studentsid,method)
{

var answer = confirm(“Do you really want to delete this record ?”);
if (answer){
document.getElementById(“coursesid”).value=studentsid;
document.getElementById(“method”).value=method;
document.forms[“searchcourseForm”].submit();
return true;
}
else{
return false;
}

}
function doMultiOper(param,field,method)
{
if(param!=-1)
{
var counter=0;
for (i = 0; i < field.length; i++)
{
if(field[i].checked == true)
{
counter=1
break;
}
}
if(counter==1)
{
var answer = confirm(“Do you really want to delete this record ?”);
if (answer){

document.getElementById(“method”).value=method;
document.forms[“searchcourseForm”].submit();
return true;
}
else
{
return false;
}
}
else
{
alert(“Please select records atleat one!”);
return false;
}
}
}
</script>
</head>
<body>
<html:form action=”searchcourse.do”>

<table width=”700px”>
<tr>
<td width=”5%”>&nbsp;</td><td width=”20%”>&nbsp;</td><td width=”20%”>&nbsp;</td><td width=”20%”>Action :</td>
<td width=”35%”>
<select name=”oper” id=”oper” onchange=”doMultiOper(this.value,document.searchcourseForm.chk,’multidelete’);”>
<option value=”-1″>Select</option>
<option value=”delete”>Delete</option>
</select>

</td>
</tr>
<tr><td width=”5%”><input type=”checkbox” name=”chkall” onClick=”checkuncheck(document.searchcourseForm.chk)” /></td><td width=”20%”>Course Id</td><td width=”20%”>Course</td><td width=”20%”>Student</td><td width=”35%”>Action</td></tr>
<%
List searchresult = (List) request.getAttribute(“searchresult”);
%>
<%
for(Iterator itr=searchresult.iterator(); itr.hasNext(); )
{
Object[] obj_list =(Object[])itr.next();
%>

<tr>
<td><input type=”checkbox” name=”chk” value=”<%=obj_list[0] %>” /></td>

<td><%=obj_list[0] %></td>
<td><%=obj_list[1] %></td>
<td><%=obj_list[2] %></td>
<td>
<a href=”javascript:void(0);”  onClick=window.open(“editcourse.do?coursesid=<%=obj_list[0] %>&method=edit”,”Course”,”width=550,height=170,0,status=0,”);  >Edit</a>&nbsp;|&nbsp;
<a href=”javascript:void(0);” onclick=”doOper(‘<%=obj_list[0] %>’,’delete’);” >Delete</a>
</td>
</tr>

<%
}
%>

</table>
<html:hidden property=”keyword” styleId=”keyword” value=”<%=(String)request.getAttribute(“keyword”) %>” />
<html:hidden property=”method” styleId=”method” value=”” />
<input type=”hidden” name=”coursesid” id=”coursesid” value=”” />

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

hibernate and strut integration


STEP 1:DATABASE STRUCTURE


— Database: `college`

— ——————————————————–


— Table structure for table `courses`

CREATE TABLE IF NOT EXISTS `courses` (
`course_id` int(11) NOT NULL AUTO_INCREMENT,
`course_name` varchar(50) NOT NULL,
PRIMARY KEY (`course_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;


— Dumping data for table `courses`

INSERT INTO `courses` (`course_id`, `course_name`) VALUES
(1, ‘MCA’),
(2, ‘MBA’),
(3, ‘BSC’),
(4, ‘BE-IT’),
(6, ‘CA’);

— ——————————————————–


— Table structure for table `students`

CREATE TABLE IF NOT EXISTS `students` (
`studentsid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`course_id` int(11) NOT NULL,
PRIMARY KEY (`studentsid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;


— Dumping data for table `students`

INSERT INTO `students` (`studentsid`, `name`, `course_id`) VALUES
(1, ‘Henry’, 1),
(2, ‘Mike’, 1),
(3, ‘Fisher’, 2),
(4, ‘Jessica’, 3),
(5, ‘Kalley’, 4),
(6, ‘Gid’, 6);
========================================================
STEP 2: Courses.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”&gt;
<!–
Mapping file autogenerated by MyEclipse Persistence Tools
–>
<hibernate-mapping>
<class name=”courses.Courses” table=”courses” catalog=”college”>
<id name=”courseId” type=”java.lang.Integer”>
<column name=”course_id” />
<generator />
</id>
<property name=”courseName” type=”java.lang.String”>
<column name=”course_name” length=”50″ not-null=”true” />
</property>
</class>
</hibernate-mapping>

=======================================================================================
STEP 3: Students.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”&gt;
<!–
Mapping file autogenerated by MyEclipse Persistence Tools
–>
<hibernate-mapping>
<class name=”students.Students” table=”students” catalog=”college”>
<id name=”studentsid” type=”java.lang.Integer”>
<column name=”studentsid” />
<generator />
</id>
<property name=”name” type=”java.lang.String”>
<column name=”name” length=”50″ not-null=”true” />
</property>
<property name=”courseId” type=”java.lang.Integer”>
<column name=”course_id” not-null=”true” />
</property>
<!– <many-to-one name=”courseId” column=”course_id”/>  –>
</class>
</hibernate-mapping>

=================================================================================
STEP 4:Courses.java
package courses;

/**
* Courses entity. @author MyEclipse Persistence Tools
*/

public class Courses implements java.io.Serializable {

// Fields

private Integer courseId;
private String courseName;

// Constructors

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

/** full constructor */
public Courses(String courseName) {
this.courseName = courseName;
}

// Property accessors

public Integer getCourseId() {
return this.courseId;
}

public void setCourseId(Integer courseId) {
this.courseId = courseId;
}

public String getCourseName() {
return this.courseName;
}

public void setCourseName(String courseName) {
this.courseName = courseName;
}

}

=========================================================================
STEP 5:Students.java
package students;

import courses.Courses;

/**
* Students entity. @author MyEclipse Persistence Tools
*/

public class Students implements java.io.Serializable {

// Fields

private Integer studentsid;
private String name;
private Integer courseId;

// Constructors

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

/** full constructor */
public Students(String name, Integer courseId) {
this.name = name;
this.courseId = courseId;
}

// Property accessors

public Integer getStudentsid() {
return this.studentsid;
}

public void setStudentsid(Integer studentsid) {
this.studentsid = studentsid;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public Integer getCourseId() {
return this.courseId;
}

public void setCourseId(Integer courseId) {
this.courseId = courseId;
}

}

==============================================================================
STEP 6: hibernate.cfg.xml

org.hibernate.dialect.MySQLDialect
jdbc:mysql://localhost/college
root
com.mysql.jdbc.Driver
cmdriver

===============================================================================
STEP :7 SearchcourseAction.java

package courses;

import java.util.Iterator;
import java.util.List;

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;
import courses.SearchcourseForm;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import students.Students;

/**
* MyEclipse Struts
* Creation date: 06-07-2011
*
* XDoclet definition:
* @struts.action path=”/searchcourse” name=”searchcourseForm” input=”searchcourse.jsp” scope=”request” validate=”true”
* @struts.action-forward name=”sucess” path=”searchresult.jsp”
* @struts.action-forward name=”fail” path=”searchcourse.jsp”
*/
public class SearchcourseAction extends Action {
/*
* Generated Methods
*/

/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
SearchcourseForm searchcourseForm = (SearchcourseForm) form;// TODO Auto-generated method stub

String keyword=searchcourseForm.getKeyword();

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

Transaction transaction = null;

transaction = session.beginTransaction();
String SqlStr=”select courses.courseId,courses.courseName from Courses as courses ,Students as students where students.courseId=courses.courseId and courses like ‘%”+keyword+”%'”;
System.out.println(SqlStr);
List courses = session.createQuery(SqlStr).list();

request.setAttribute(“searchresult”, courses);

transaction.commit();
session.close();

return mapping.findForward(“sucess”);
}
}

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

STEP : 8 SearchcourseForm.java

/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package courses;

import org.apache.struts.action.ActionForm;

/**
* MyEclipse Struts
* Creation date: 06-07-2011
*
* XDoclet definition:
* @struts.form name=”searchcourseForm”
*/
public class SearchcourseForm extends ActionForm {
/*
* Generated fields
*/

/** keyword property */
private String keyword;

/*
* Generated Methods
*/

/**
* Returns the keyword.
* @return String
*/
public String getKeyword() {
return keyword;
}

/**
* Set the keyword.
* @param keyword The keyword to set
*/
public void setKeyword(String keyword) {
this.keyword = keyword;
}
}

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

STEP :9 struts-config.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE struts-config PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 1.2//EN” “http://struts.apache.org/dtds/struts-config_1_2.dtd”&gt;

<struts-config>
<data-sources />
<form-beans >
<form-bean name=”searchcourseForm” type=”courses.SearchcourseForm” />

</form-beans>

<global-exceptions />
<global-forwards />
<action-mappings >
<action
attribute=”searchcourseForm”
input=”searchcourse.jsp”
name=”searchcourseForm”
path=”/searchcourse”
scope=”request”
type=”courses.SearchcourseAction”>
<set-property property=”cancellable” value=”true” />
<forward name=”sucess” path=”/searchresult.jsp” />
<forward name=”fail” path=”/searchcourse.jsp” />
</action>

</action-mappings>

<message-resources parameter=”com.yourcompany.struts.ApplicationResources” />
</struts-config>
============================================================================================

STEP : 10 searchcourse.jsp

<%@ page language=”java” pageEncoding=”UTF-8″%>
<%@ taglib uri=”http://struts.apache.org/tags-bean&#8221; prefix=”bean”%>
<%@ taglib uri=”http://struts.apache.org/tags-html&#8221; prefix=”html”%>

<html>
<head>
<title>JSP for SearchcourseForm form</title>
</head>
<body>
<html:form action=”/searchcourse”>
keyword : <html:text property=”keyword”/><html:errors property=”keyword”/><br/>
<html:submit/><html:cancel/>
</html:form>
</body>
</html>
===============================================================================

STEP : 11  searchresult.jsp

<%@ page language=”java” pageEncoding=”UTF-8″%>
<%@ taglib uri=”http://struts.apache.org/tags-bean&#8221; prefix=”bean”%>
<%@ taglib uri=”http://struts.apache.org/tags-html&#8221; prefix=”html”%>
<%@page language=”java” import=”java.util.*”%>

<html>
<head>
<title>JSP for SearchcourseForm form</title>
</head>
<body>
<html:form action=”/searchcourse”>

<table>
<tr><td>Id</td><td>Name</td></tr>
<%
List searchresult = (List) request.getAttribute(“searchresult”);
%>
<%
for(Iterator itr=searchresult.iterator(); itr.hasNext(); )
{
Object[] obj_list =(Object[])itr.next();
%>

<tr><td><%=obj_list[0] %></td><td><%=obj_list[1] %></td></tr>

<%
}
%>

</table>

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

 

many to one mapping in hibernate


STEP 1:DATABASE STRUCTURE


— Database: `college`

— ——————————————————–


— Table structure for table `courses`

CREATE TABLE IF NOT EXISTS `courses` (
`course_id` int(11) NOT NULL AUTO_INCREMENT,
`course_name` varchar(50) NOT NULL,
PRIMARY KEY (`course_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;


— Dumping data for table `courses`

INSERT INTO `courses` (`course_id`, `course_name`) VALUES
(1, ‘MCA’),
(2, ‘MBA’),
(3, ‘BSC’),
(4, ‘BE-IT’),
(6, ‘CA’);

— ——————————————————–


— Table structure for table `students`

CREATE TABLE IF NOT EXISTS `students` (
`studentsid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`course_id` int(11) NOT NULL,
PRIMARY KEY (`studentsid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;


— Dumping data for table `students`

INSERT INTO `students` (`studentsid`, `name`, `course_id`) VALUES
(1, ‘Henry’, 1),
(2, ‘Mike’, 1),
(3, ‘Fisher’, 2),
(4, ‘Jessica’, 3),
(5, ‘Kalley’, 4),
(6, ‘Gid’, 6);
========================================================
STEP 2: Courses.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”&gt;
<!–
Mapping file autogenerated by MyEclipse Persistence Tools
–>
<hibernate-mapping>
<class name=”courses.Courses” table=”courses” catalog=”college”>
<id name=”courseId” type=”java.lang.Integer”>
<column name=”course_id” />
<generator />
</id>
<property name=”courseName” type=”java.lang.String”>
<column name=”course_name” length=”50″ not-null=”true” />
</property>
</class>
</hibernate-mapping>

=======================================================================================
STEP 3: Students.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”&gt;
<!–
Mapping file autogenerated by MyEclipse Persistence Tools
–>
<hibernate-mapping>
<class name=”students.Students” table=”students” catalog=”college”>
<id name=”studentsid” type=”java.lang.Integer”>
<column name=”studentsid” />
<generator />
</id>
<property name=”name” type=”java.lang.String”>
<column name=”name” length=”50″ not-null=”true” />
</property>
<!–  <property name=”courseId” type=”java.lang.Integer”>
<column name=”course_id” not-null=”true” />
</property>
–>
<many-to-one name=”courseId” column=”course_id”/>
</class>
</hibernate-mapping>

=================================================================================
STEP 4:Courses.java
package courses;

/**
* Courses entity. @author MyEclipse Persistence Tools
*/

public class Courses implements java.io.Serializable {

// Fields

private Integer courseId;
private String courseName;

// Constructors

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

/** full constructor */
public Courses(String courseName) {
this.courseName = courseName;
}

// Property accessors

public Integer getCourseId() {
return this.courseId;
}

public void setCourseId(Integer courseId) {
this.courseId = courseId;
}

public String getCourseName() {
return this.courseName;
}

public void setCourseName(String courseName) {
this.courseName = courseName;
}

}
=========================================================================
STEP 5:Students.java
package students;

import courses.Courses;

/**
* Students entity. @author MyEclipse Persistence Tools
*/

public class Students implements java.io.Serializable {

// Fields

private Integer studentsid;
private String name;
private Courses courseId;

// Constructors

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

/** full constructor */
public Students(String name, Courses courseId) {
this.name = name;
this.courseId = courseId;
}

// Property accessors

public Integer getStudentsid() {
return this.studentsid;
}

public void setStudentsid(Integer studentsid) {
this.studentsid = studentsid;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public Courses getCourseId() {
return this.courseId;
}

public void setCourseId(Courses courseId) {
this.courseId = courseId;
}

}
==============================================================================
STEP 6: hibernate.cfg.xml

 

org.hibernate.dialect.MySQLDialect
jdbc:mysql://localhost/college
root
com.mysql.jdbc.Driver
cmdriver

===============================================================================
STEP :7 demo.java
package courses;

import java.util.List;
import java.util.Iterator;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import students.Students;

public class demo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

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

Transaction transaction = null;

transaction = session.beginTransaction();
Courses course = new Courses();
course.setCourseName(“CA”);
session.save(course);
transaction.commit();

transaction = session.beginTransaction();
Students student = new Students();
student.setName(“Gid”);
student.setCourseId(course);
session.save(student);
transaction.commit();
session.close();

}

}

join query in hibernate step by step example


STEP 1:DATABASE STRUCTURE


— Database: `college`

— ——————————————————–


— Table structure for table `courses`

CREATE TABLE IF NOT EXISTS `courses` (
`course_id` int(11) NOT NULL AUTO_INCREMENT,
`course_name` varchar(50) NOT NULL,
PRIMARY KEY (`course_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;


— Dumping data for table `courses`

INSERT INTO `courses` (`course_id`, `course_name`) VALUES
(1, ‘MCA’),
(2, ‘MBA’),
(3, ‘BSC’),
(4, ‘BE-IT’),
(6, ‘CA’);

— ——————————————————–


— Table structure for table `students`

CREATE TABLE IF NOT EXISTS `students` (
`studentsid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`course_id` int(11) NOT NULL,
PRIMARY KEY (`studentsid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;


— Dumping data for table `students`

INSERT INTO `students` (`studentsid`, `name`, `course_id`) VALUES
(1, ‘Henry’, 1),
(2, ‘Mike’, 1),
(3, ‘Fisher’, 2),
(4, ‘Jessica’, 3),
(5, ‘Kalley’, 4),
(6, ‘Gid’, 6);
========================================================
STEP 2: Courses.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”&gt;
<!–
Mapping file autogenerated by MyEclipse Persistence Tools
–>
<hibernate-mapping>
<class name=”courses.Courses” table=”courses” catalog=”college”>
<id name=”courseId” type=”java.lang.Integer”>
<column name=”course_id” />
<generator />
</id>
<property name=”courseName” type=”java.lang.String”>
<column name=”course_name” length=”50″ not-null=”true” />
</property>
</class>
</hibernate-mapping>

=======================================================================================
STEP 3: Students.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”&gt;
<!–
Mapping file autogenerated by MyEclipse Persistence Tools
–>
<hibernate-mapping>
<class name=”students.Students” table=”students” catalog=”college”>
<id name=”studentsid” type=”java.lang.Integer”>
<column name=”studentsid” />
<generator />
</id>
<property name=”name” type=”java.lang.String”>
<column name=”name” length=”50″ not-null=”true” />
</property>
<!–  <property name=”courseId” type=”java.lang.Integer”>
<column name=”course_id” not-null=”true” />
</property>
–>
<many-to-one name=”courseId” column=”course_id”/>
</class>
</hibernate-mapping>

=================================================================================
STEP 4:Courses.java
package courses;

/**
* Courses entity. @author MyEclipse Persistence Tools
*/

public class Courses implements java.io.Serializable {

// Fields

private Integer courseId;
private String courseName;

// Constructors

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

/** full constructor */
public Courses(String courseName) {
this.courseName = courseName;
}

// Property accessors

public Integer getCourseId() {
return this.courseId;
}

public void setCourseId(Integer courseId) {
this.courseId = courseId;
}

public String getCourseName() {
return this.courseName;
}

public void setCourseName(String courseName) {
this.courseName = courseName;
}

}
=========================================================================
STEP 5:Students.java
package students;

import courses.Courses;

/**
* Students entity. @author MyEclipse Persistence Tools
*/

public class Students implements java.io.Serializable {

// Fields

private Integer studentsid;
private String name;
private Courses courseId;

// Constructors

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

/** full constructor */
public Students(String name, Courses courseId) {
this.name = name;
this.courseId = courseId;
}

// Property accessors

public Integer getStudentsid() {
return this.studentsid;
}

public void setStudentsid(Integer studentsid) {
this.studentsid = studentsid;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public Courses getCourseId() {
return this.courseId;
}

public void setCourseId(Courses courseId) {
this.courseId = courseId;
}

}
==============================================================================
STEP 6: hibernate.cfg.xml

 

org.hibernate.dialect.MySQLDialect
jdbc:mysql://localhost/college
root
com.mysql.jdbc.Driver
cmdriver

===============================================================================
STEP :7 demo.java
package courses;

import java.util.List;
import java.util.Iterator;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import students.Students;

public class demo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

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

Transaction transaction = null;

transaction = session.beginTransaction();
String SqlStr=”select courseId,courseName from Courses where courseId=(select courseId from Students where studentsid=1)”;
List courses = session.createQuery(SqlStr).list();

for(Iterator it=courses.iterator();it.hasNext();)
{
Object[] obj_list=(Object[])it.next();

System.out.println(obj_list[0]);
}

transaction.commit();
session.close();

}

}

getting records from database in hibernate


Way 1:

Remark : when you want to get limited no of fields from database, at that time, it is necessary to use object array.

 

public static void main(String[] args) {
// TODO Auto-generated method stub

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

Transaction transaction = null;

transaction = session.beginTransaction();
List courses = session.createQuery(“select courseId,courseName from Courses”).list();
for(Iterator it=courses.iterator();it.hasNext();)
{

Object[] object = (Object[])it.next();
System.out.println(object[0]);
System.out.println(object[1]);
}

transaction.commit();
session.close();

}

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

Way 2:

Remark : when you want to get one fields from database, at that time.

public static void main(String[] args) {
// TODO Auto-generated method stub

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

Transaction transaction = null;

transaction = session.beginTransaction();
List courses = session.createQuery(“select courseName from Courses”).list();

for(Iterator it=courses.iterator();it.hasNext();)
{
//Courses course=(Courses)it.next();
String couresename = (String)it.next();
System.out.println(couresename);
}

transaction.commit();

session.close();

}

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

Way 3:

Remark : when you want to get all fields from database, at that time.

public static void main(String[] args) {
// TODO Auto-generated method stub

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

Transaction transaction = null;

transaction = session.beginTransaction();
List courses = session.createQuery(“from Courses”).list();

for(Iterator it=courses.iterator();it.hasNext();)
{
Courses course=(Courses)it.next();
System.out.println(course.getCourseName());
}

transaction.commit();
session.close();

}

Mapping problem in hibernate


there should be same table name in query which belong to pojo class….

for example

suppose you have made Courses.java pojo class then
you must take class name “Courses” in query as table.

example
List list=session.createQuery(“from Courses”).list();

here from Courses ( it is name of pojo class);