Wednesday, November 19, 2014

Creating Simple Hibernate Struts 2 page

Creating a simple page where user inputs user ID and fetch data from  DATABASE , with the help of hibernate.


DataBase:hiber

CREATE TABLE `hiber`.`emp` (
  `id` INT NOT NULL,
  `name` VARCHAR(45) NULL,
  `salary` INT NULL);
---------------------------------------------------------------------

Struts.XML

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
  
   
    <package name="connecthiber" extends="struts-default" >

        <action name="form1"
          class="connecthiber.ConnectAction" method="execute">
         <result name="success">welcome.jsp</result>
            
        </action>
        
    </package>
    
</struts>

---------------------------------------------------------------------

welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HIBERNATE example</title>

</head>
<body>
<s:form action="form1" method="post">
<s:textfield name="searchid"></s:textfield>
<s:submit value="Search" align="center" />
</s:form>
<h2>Employee</h2>
<table>
<tr>
<th>Name</th>
<th>Salary</th>

</tr>
<s:iterator value="contactList" var="Emp">
<tr>
<td><s:property value="name" /></td>
<td><s:property value="salary" /></td>

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

</body>

</html>




---------------------------------------------------------------------
ConnectManager.java

package connecthiber;

import hiber.HibernateUtil;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
public class ConnectManager extends HibernateUtil{

public int searchid=1;
@SuppressWarnings("unchecked")
public List<Emp> list(int searchid) {
     
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
     
List<Emp> contacts  = null;
    try {
        String hql = "FROM Emp E WHERE E.id = :searchid";
        Query query = session.createQuery(hql);
        query.setParameter("searchid",searchid);
        contacts = query.list();
       
     /*contacts = (List<Emp>)session.createQuery("from Emp e where e.id=:searchid").setParameter("searchid",searchid).list();*/


        session.getTransaction().commit();
        return contacts;
        }
    catch (HibernateException e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        }
    session.getTransaction().commit();
    return contacts;
     
    }


}
---------------------------------------------------------------------
ConnectAction.java

package connecthiber;

import connecthiber.Emp;
import connecthiber.ConnectManager;

import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class ConnectAction extends ActionSupport {




private List<Emp> contactList;
private int searchid;


/**
* @return the searchid
*/
public int getSearchid() {
return searchid;
}

/**
* @param searchid the searchid to set
*/
public void setSearchid(int searchid) {
this.searchid = searchid;
}

public List<Emp> getContactList() {
return contactList;
}

/**
* @param contactList
*            the contactList to set
*/
public void setContactList(List<Emp> contactList) {
this.contactList = contactList;
}




public String execute() {
String ret;
ConnectManager connectManager = new ConnectManager();


try {

contactList = connectManager.list(searchid);

System.out.println("execute called");

ret = "success";
} catch (Exception e) {
System.out.println(e.getMessage());
ret = " error";
}
return ret;
}

}
---------------------------------------------------------------------
Emp.java

package connecthiber;
import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
@Entity
@Table(name="emp")
public class Emp implements Serializable{


@Column(name="id")
private int id;
@Column(name="name") 
private String name;
@Column(name="salary")
   private Long salary;
/**
* @return the id
*/
@Id
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the salary
*/
public Long getSalary() {
return salary;
}
/**
* @param salary the salary to set
*/
public void setSalary(Long salary) {
this.salary = salary;
}
}

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">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">
            com.mysql.jdbc.Driver
        </property>
        <property name="connection.url">
            jdbc:mysql://localhost:3306/hiber
        </property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.pool_size">10</property>
        <property name="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="connecthiber.Emp" />
    </session-factory>
</hibernate-configuration>

HibernateUtil.java
---------------------------------------------------------------------
package hiber;



import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
@SuppressWarnings("deprecation")
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;
    }
}



---------------------------------------------------------------------
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>hiber</display-name>
   <welcome-file-list>
       <welcome-file>welcome.jsp</welcome-file>
   </welcome-file-list>
  
   <filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> 
</web-app>

No comments:

Post a Comment