STRUTS2HIBERNATE2 ONE TO ONE ANNOTAION MAPPING

<div dir="ltr" style="text-align: left;" trbidi="on">
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,
  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,
result_student_id integer,
 
  CONSTRAINT studentid PRIMARY KEY (studentid )
)
WITH (
  OIDS=FALSE
);
ALTER TABLE studentdetails
  OWNER TO postgres;







2.web.xml


<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



<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false">
<constant name="struts.devMode" value="true">
<package extends="struts-default" name="default" namespace="/">

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

4 create hibernate.cfg.xml in source Package



<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">
</mapping></mapping></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.OneToOne;
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;
    @OneToOne(targetEntity=Result.class,cascade=CascadeType.ALL)
    @JoinColumn(name="result_student_id",referencedColumnName="resultid")
    private Result 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 Result getResult() {
        return result;
    }

    public void setResult(Result 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 node3
 */

@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 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 void setResultSet(Set resultSet) {
        this.resultSet = resultSet;
    }

    public String view() {
        this.studentDetailsList = studentManager.list();
        for (int i = 0; i &lt; studentDetailsList.size(); i++) {
        }
        RadioButtonAction();
        DropDownAction();
        return SUCCESS;
    }

    public String add() {

        try {
            studentManager.add(studentDetails);
            this.studentDetailsList = studentManager.list();
            RadioButtonAction();
            DropDownAction();
            return SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }


    }

    public String delete() {
        studentManager.delete(getId());
        this.studentDetailsList = studentManager.list();
        RadioButtonAction();
        DropDownAction();
        return SUCCESS;

    }

    public String edit() {
        //this.groupBooking=groupBookingManager.edit(getId());
        this.studentDetailsList = studentManager.list();
        RadioButtonAction();
        DropDownAction();
        return SUCCESS;
    }
}


10 create index.jsp in Web Pages

&lt;%--
Document : index
Created on : 19 Dec, 2012, 12:21:23 PM
Author : Krishnadas V A
--%&gt;





11 create students.jsp in Web Pages

&lt;%--
    Document   : students
    Created on : 19 Dec, 2012, 3:06:09 PM
    Author     : Krishnadas V A
--%&gt;

&lt;%@ page contentType="text/html; charset=UTF-8"%&gt;
&lt;%@ taglib prefix="s" uri="/struts-tags"%&gt;

<html>
    <head>
       
        <title>Students</title>
    </head>
    <body>
        <s:form action="addstudent" name="addstudent">
            <s:textfield label="Student name" name="studentDetails.studentName">
            <s:radio label="Gender" list="gender" name="studentDetails.studentGender">
            <s:textfield label="Class" name="studentDetails.studentClass">
            <s:textfield label="Semester1" name="studentDetails.result.semester">
            <s:textfield label="Mark1" name="studentDetails.result.mark">
           
            <s:select headerkey="-1" headervalue="select Division" label="Division" list="division" name="studentDetails.studentDivision">
            <s:submit label="submit" name="submit">
        </s:submit></s:select></s:textfield></s:textfield></s:textfield></s:radio></s:textfield></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>
               
            </tr>
<s:iterator status="studentDetails" value="studentDetailsList">
<tr>
                    <td><s:property value="studentId"> </s:property></td>

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

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

                </tr>
</s:iterator>
        </table>
</body>
</html>



</studentdetails></result></result></studentdetails></string></string></string></string></string></string></result></studentdetails></studentdetails></studentdetails></studentdetails></div>

DownLoad source code here

Comments

  1. Thank you so much krishnadas, that works for me .. very simple and reliable steps.. keep going..

    ReplyDelete
    Replies
    1. happy to hear that sanjay..for more queries contact me: vakrishnadas@gmail.com

      Delete

Post a Comment

Popular posts from this blog

Python mechanize For Browsing

Django Dynamic Formsets with Jquery

Liferay/MuleSoft Integration Provides Low-Cost Enterprise Java Alternative