STRUTS2HIBERNATE2 ONE TO MANY ANNOTAION MAPPING




1.postgres sql query
create database as student

-- Table: result

-- DROP TABLE result;

CREATE TABLE result
(
resultid bigserial NOT NULL,
semester character varying(250) NOT NULL,
mark character varying(250) NOT NULL,
result_student_id integer,
CONSTRAINT resultid PRIMARY KEY (resultid )
)
WITH (
OIDS=FALSE
);
ALTER TABLE result
OWNER TO postgres;

-- Table: studentdetails

-- DROP TABLE studentdetails;

CREATE TABLE studentdetails
(
studentid bigserial NOT NULL,
studentname character varying(250) NOT NULL,
studentgender character varying(250) NOT NULL,
studentclass character varying(250) NOT NULL,
studentdivision character varying(250) NOT NULL,
CONSTRAINT studentid PRIMARY KEY (studentid )
)
WITH (
OIDS=FALSE
);
ALTER TABLE studentdetails
OWNER TO postgres;


2.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>Student</display-name>
<context-param>
<param-name>tilesDefinitions</param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
<!--filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class-->
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>



3 create struts.xml in source Pakage

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts SYSTEM "struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="default" extends="struts-default" namespace="/">

<action name="test">
<result>test.jsp</result>
</action>
<action name="one" class="com.inzane.student.action.StudentAction" method="view">
<result name="success">/students.jsp</result>
</action>
<action name="addstudent" class="com.inzane.student.action.StudentAction" method="add">
<result name="success">students.jsp</result>
</action>
<action name="delete" class="com.inzane.student.action.StudentAction" method="delete">
<result name="success">students.jsp</result>
</action>
<action name="edit" class="com.inzane.student.action.StudentAction" method="edit">
<result name="success">editstudent.jsp</result>
</action>
</package>
</struts>

4 create hibernate.cfg.xml in source Package

<?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="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/student</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">qwerty</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.inzane.student.model.StudentDetails" />
<mapping class="com.inzane.student.model.Result" />
</session-factory>
</hibernate-configuration>

5 create HibernateUtil in source Package com.inzane.student.Util


package com.inzane.student.Util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}


6 create StudentDetails entity class in source package com.inzane.student.model

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.inzane.student.model;

import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
*
* @author Krishnadas V A
*/
@Entity
@Table(name = "studentdetails")
public class StudentDetails {

@Id
@GeneratedValue
@Column(name = "studentid")
private Long studentId;
@Column(name = "studentname")
private String studentName;
@Column(name = "studentgender")
private String studentGender;
@Column(name = "studentclass")
private String studentClass;
@Column(name = "studentdivision")
private String studentDivision;
@OneToMany(targetEntity = Result.class, cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name = "result_student_id", referencedColumnName = "studentid")
private Set result;


public Long getStudentId() {
return studentId;
}

public void setStudentId(Long studentId) {
this.studentId = studentId;
}

public String getStudentName() {
return studentName;
}

public void setStudentName(String studentName) {
this.studentName = studentName;
}

public String getStudentGender() {
return studentGender;
}

public void setStudentGender(String studentGender) {
this.studentGender = studentGender;
}

public String getStudentClass() {
return studentClass;
}

public void setStudentClass(String studentClass) {
this.studentClass = studentClass;
}

public String getStudentDivision() {
return studentDivision;
}

public void setStudentDivision(String studentDivision) {
this.studentDivision = studentDivision;
}
public Set getResult() {
return result;
}

public void setResult(Set result) {
this.result = result;
}
}

7 create Result entity class in source package com.inzane.student.model
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.inzane.student.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
*
* @author Krishnadas v a
*/

@Entity
@Table(name = "result")
public class Result {
@Id
@GeneratedValue
@Column(name = "resultid")
private Long resultId;
@Column(name = "semester")
private String semester;
@Column(name = "mark")
private String mark;
public Long getResultId(){
return resultId;
}
public void setResultId(Long resultId){
this.resultId= resultId;
}
public String getSemester(){
return semester;
}
public void setSemester(String semester){
this.semester= semester;
}
public String getMark(){
return mark;
}
public void setMark(String mark){
this.mark= mark;
}
}


8 create StudentManager in sourcePackage com.inzane.student.controller


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.inzane.student.controller;

import com.inzane.student.Util.HibernateUtil;
import com.inzane.student.model.StudentDetails;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.classic.Session;

/**
*
* @author Krishnadas V A
*/
public class StudentManager {
@SuppressWarnings("unchecked")

public void add(StudentDetails studentDetails) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.saveOrUpdate(studentDetails);
session.getTransaction().commit();
//return groupBooking;
}

public StudentDetails delete(Long id) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
System.out.println("delete id"+id);
StudentDetails studentDetails = (StudentDetails) session.load(StudentDetails.class, id);
if (null != studentDetails) {
session.delete(studentDetails);
}
session.getTransaction().commit();
return studentDetails;
}

public List<StudentDetails> list() {

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
//session.beginTransaction();
List<StudentDetails> studentDetails = null;
try {
session.beginTransaction();
studentDetails = (List<StudentDetails>) session.createQuery("from StudentDetails").list();
session.getTransaction().commit();
} catch (HibernateException e) {
e.printStackTrace();
//session.getTransaction().rollback();
}
//session.getTransaction().commit();
return studentDetails;
}

}

9.create StudentAction in source Package com.inzane.student.action

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.inzane.student.action;

import com.inzane.student.controller.StudentManager;
import com.inzane.student.model.Result;
import com.inzane.student.model.StudentDetails;
import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;

/**
*
* @author Krishnadas V A
*/
public class StudentAction extends ActionSupport {

private StudentDetails studentDetails = new StudentDetails();
private Result result = new Result();
private Result result1 = new Result();
private List<StudentDetails> studentDetailsList;
private List<Result> resultList;
private Set resultSet=new HashSet();
private Long id;
private StudentManager studentManager;
private List<String> gender;
private List<String> division;

public StudentAction() {
studentManager = new StudentManager();

}

public void RadioButtonAction() {
gender = new ArrayList<String>();
gender.add("Male");
gender.add("Female");

}

public void DropDownAction() {
division = new ArrayList<String>();
division.add("A");
division.add("B");
division.add("C");
division.add("D");
division.add("E");

}

public List getgender() {
return gender;

}

public List getdivision() {
return division;

}

public void setgender(List<String> gender) {
this.gender = gender;

}

public void setdivision(List<String> division) {
this.division = division;

}

public Long getId() {
return id;
}

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

public StudentDetails getStudentDetails() {
return studentDetails;
}

public List<StudentDetails> getStudentDetailsList() {
return studentDetailsList;
}
public List<Result> getResultList() {
return resultList;
}
public void setResultList(List<Result> resultList) {
this.resultList = resultList;
}

public void setStudentDetails(StudentDetails studentDetails) {
this.studentDetails = studentDetails;
}

public void setStudentDetailsList(List<StudentDetails> studentDetailsList) {
this.studentDetailsList = studentDetailsList;
}

public Result getResult() {
return result;
}

public Result getResult1() {
return result1;
}

public Set getResultSet() {
return resultSet;
}

public void setResult(Result result) {
this.result = result;
}

public void setResult1(Result result1) {
this.result1 = result1;
}

public void setResultSet(Set resultSet) {
this.resultSet = resultSet;
}

public String view() {
System.out.println("studentDetails view 0");
this.studentDetailsList = studentManager.list();
for(int i=0;i<studentDetailsList.size();i++){
System.out.println("getStudentName :" + studentDetailsList);
System.out.println("getStudentName :" + this.studentDetailsList.get(i).getStudentName());
System.out.println("getStudentGender :" + this.studentDetailsList.get(i).getStudentGender());
System.out.println("getStudentClass :" + this.studentDetailsList.get(i).getStudentClass());
System.out.println("getStudentDivision :" + this.studentDetailsList.get(i).getStudentDivision());
System.out.println("getMarks :" + this.studentDetailsList.get(i).getResult());
}
System.out.println("studentDetails view 1");
RadioButtonAction();
System.out.println("studentDetails view 2");
DropDownAction();
System.out.println("studentDetails view 3");
return SUCCESS;

}

public String add() {
System.out.println("studentDetails add 1");

try {

System.out.println("getStudentName no:" + studentDetails.getStudentName());
System.out.println("getStudentGender no:" + studentDetails.getStudentGender());
System.out.println("getStudentClass no:" + studentDetails.getStudentClass());
System.out.println("getStudentDivision no:" + studentDetails.getStudentDivision());
System.out.println("About to Save studentDetails object:" + studentDetails);
this.resultSet.add(result);
this.resultSet.add(result1);
studentDetails.setResult(resultSet);
studentManager.add(studentDetails);
System.out.println("studentDetails object Saved:" + studentDetails);

this.studentDetailsList = studentManager.list();
System.out.println("size of list :" + this.studentDetailsList.size());

System.out.println("studentDetails add 3");
RadioButtonAction();
System.out.println("studentDetails add 4");
DropDownAction();
System.out.println("studentDetails add 5");
return SUCCESS;
} catch (Exception e) {
System.out.println("studentDetails add 1-exception:" + e.getLocalizedMessage());
e.printStackTrace();
return ERROR;
}


}

public String delete() {
studentManager.delete(getId());
System.out.println("studentDetails view 0");
this.studentDetailsList = studentManager.list();
for (int i = 0; i < studentDetailsList.size(); i++) {
System.out.println("getStudentName :" + this.studentDetailsList.get(i).getStudentName());
System.out.println("getStudentGender :" + this.studentDetailsList.get(i).getStudentGender());
System.out.println("getStudentClass :" + this.studentDetailsList.get(i).getStudentClass());
System.out.println("getStudentDivision :" + this.studentDetailsList.get(i).getStudentDivision());
}
System.out.println("studentDetails view 1");
RadioButtonAction();
System.out.println("studentDetails view 2");
DropDownAction();
System.out.println("studentDetails view 3");
return SUCCESS;

}

public String edit() {
//this.groupBooking=groupBookingManager.edit(getId());
System.out.println("studentDetails edit 1");
this.studentDetailsList = studentManager.list();
for (int i = 0; i < studentDetailsList.size(); i++) {
if (studentDetailsList.get(i).getStudentId().equals(getId())) {
this.studentDetails = studentDetailsList.get(i);
System.out.println("studentDetails to edit:"+studentDetails);
for(int j=0;j<studentDetailsList.get(i).getResult().size();j++){
this.resultSet=studentDetailsList.get(i).getResult();
System.out.println("size of resultSet to edit:"+resultSet.size());
resultList=new ArrayList<Result>(resultSet);
this.result=resultList.get(0);
this.result1=resultList.get(1);
}
}
}
System.out.println("studentDetails edit 1");
RadioButtonAction();
System.out.println("studentDetails edit 2");
DropDownAction();
System.out.println("studentDetails edit 3");
return SUCCESS;
}

public String test() {
System.out.println("test method in StudentAction called.");
return SUCCESS;
}
}


10 create index.jsp in Web Pages

<%--
Document : index
Created on : 19 Dec, 2012, 12:21:23 PM
Author : Krishnadas V A
--%>

<META HTTP-EQUIV="Refresh" CONTENT="0;URL=one">



11 create students.jsp in Web Pages

<%--
Document : students
Created on : 19 Dec, 2012, 3:06:09 PM
Author : Krishnadas V A
--%>

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Students</title>
</head>
<body>
<s:form name="addstudent" action="addstudent">
<s:textfield name="studentDetails.studentName" label="Student name" />
<s:radio name="studentDetails.studentGender" label="Gender" list="gender" />
<s:textfield name="studentDetails.studentClass" label="Class" />
<s:textfield name="result.semester" label="Semester1" />
<s:textfield name="result.mark" label="Mark1" />
<s:textfield name="result1.semester" label="Semester2" />
<s:textfield name="result1.mark" label="Mark2" />
<s:select name="studentDetails.studentDivision" label="Division" headerKey="-1" headerValue="select Division" list="division" />
<s:submit name="submit" label="submit"/>
</s:form>
<h3>Student list</h3>
<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Gender</th>
<th>Class</th>
<th>Marks</th>
<th>Division</th>
<th>Action</th>
</tr>
<s:iterator value="studentDetailsList" status="studentDetails" >
<tr>
<td><s:property value="studentId"/> </td>

<td><s:property value="studentName"/></td>
<td><s:property value="studentGender"/></td>

<td><s:property value="studentClass"/></td>
<td><s:iterator value="result" status="Result" >
Sem:<s:property value="semester"/>mark:<s:property value="mark"/><br>
</s:iterator></td>
<td><s:property value="studentDivision"/></td>
</tr>
</s:iterator>
</table>
</body>
</html>

Comments

  1. probably the only full-fledged sample available on net on the subject.very useful.code size may get reduced if Guice or Spring is also used.

    ReplyDelete

Post a Comment

Popular posts from this blog

Python mechanize For Browsing

Django Dynamic Formsets with Jquery

Editor TinyMCE in Django admin