Showing posts with label JPA. Show all posts
Showing posts with label JPA. Show all posts

26.Displaying Employees by Department Number Using JPA

Saturday, February 5, 2011 Posted by Sudarsan 0 comments
In this post we are going learn how to display Employee details based on the Department number, here Employee details are available in Emp details, for this we need to join Emp, Dept tables in order to get desired result.

Have a look at the fallowing Images to get clear picture about the scenario.






To get the above output create the fallowing directory structure.



Now write the code for the servlets, JSPs and genarate Entity Classes from the database, then put the classes in com.model package.

The fallowing images illustrate the code available in servlets and JSPs.

index.jsp


view.jsp


Then write the code for the servlets GetDeptnoServlet.java, ViewEmpServlet.java

GetDeptnoServlet.java

public class GetDeptnoServlet extends HttpServlet {
    @Resource
    private javax.transaction.UserTransaction utx;   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            Context ctx = (Context) new InitialContext().lookup("java:comp/env");
            utx.begin();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
            Query q=em.createNamedQuery("Dept.findAll");
            List list=q.getResultList();
            utx.commit();
            request.setAttribute("list", list);
            RequestDispatcher view=request.getRequestDispatcher("/index.jsp");
            view.forward(request, response);
        }
        catch(Exception e)
        {
            out.print(e);
        }
        finally {
            out.close();
        }    } 


ViewEmpServlet.java

public class ViewEmpServlet extends HttpServlet {
    @Resource
    private javax.transaction.UserTransaction utx;       
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

           Short deptno=new Short(request.getParameter("deptno"));
           Context ctx = (Context) new InitialContext().lookup("java:comp/env");
            utx.begin();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
            Dept dept=em.find(Dept.class, deptno);
            Collection emps=dept.getEmpCollection();
            utx.commit();

            request.setAttribute("emps", emps);
            RequestDispatcher view=request.getRequestDispatcher("/view.jsp");
            view.forward(request, response);
           
        }
        catch(Exception e)
        {
            out.print(e);
        }
        finally {
            out.close();
        }
    } 


Now, the code for Entity Classes is given below !!!

Dept.java

package com.model;
import java.io.*;
import java.util.*;
import javax.persistence.*;
@Entity
@Table(name = "DEPT")
@NamedQueries({@NamedQuery(name = "Dept.findAll", query = "SELECT d FROM Dept d"),
@NamedQuery(name = "Dept.findByDeptno", query = "SELECT d FROM Dept d WHERE d.deptno = :deptno"),
@NamedQuery(name = "Dept.findByDname", query = "SELECT d FROM Dept d WHERE d.dname = :dname"),
@NamedQuery(name = "Dept.findByLoc", query = "SELECT d FROM Dept d WHERE d.loc = :loc")})
public class Dept implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "DEPTNO")
    private Short deptno;
    @Column(name = "DNAME")
    private String dname;
    @Column(name = "LOC")
    private String loc;
    @OneToMany(mappedBy = "deptno")
    private Collection empCollection;
    public Dept() {
    }

    public Dept(Short deptno) {
        this.deptno = deptno;
    }

    public Short getDeptno() {
        return deptno;
    }

    public void setDeptno(Short deptno) {
        this.deptno = deptno;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }

    public Collection getEmpCollection() {
        return empCollection;
    }

    public void setEmpCollection(Collection empCollection) {
        this.empCollection = empCollection;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (deptno != null ? deptno.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Dept)) {
            return false;
        }
        Dept other = (Dept) object;
        if ((this.deptno == null && other.deptno != null) || (this.deptno != null && !this.deptno.equals(other.deptno))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.model.Dept[deptno=" + deptno + "]";
    }

}


Emp.java

package com.model;
import java.io.*;
import java.math.*;
import java.util.*;
import javax.persistence.*;

@Entity
@Table(name = "EMP")
@NamedQueries({@NamedQuery(name = "Emp.findAll", query = "SELECT e FROM Emp e"),
@NamedQuery(name = "Emp.findByEmpno", query = "SELECT e FROM Emp e WHERE e.empno = :empno"),
@NamedQuery(name = "Emp.findByEname", query = "SELECT e FROM Emp e WHERE e.ename = :ename"),
@NamedQuery(name = "Emp.findByJob", query = "SELECT e FROM Emp e WHERE e.job = :job"),
@NamedQuery(name = "Emp.findByMgr", query = "SELECT e FROM Emp e WHERE e.mgr = :mgr"),
@NamedQuery(name = "Emp.findByHiredate", query = "SELECT e FROM Emp e WHERE e.hiredate = :hiredate"),
@NamedQuery(name = "Emp.findBySal", query = "SELECT e FROM Emp e WHERE e.sal = :sal"),
@NamedQuery(name = "Emp.findByComm", query = "SELECT e FROM Emp e WHERE e.comm = :comm")})
public class Emp implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "EMPNO")
    private Short empno;
    @Column(name = "ENAME")
    private String ename;
    @Column(name = "JOB")
    private String job;
    @Column(name = "MGR")
    private Short mgr;
    @Column(name = "HIREDATE")
    @Temporal(TemporalType.DATE)
    private Date hiredate;
    @Column(name = "SAL")
    private BigDecimal sal;
    @Column(name = "COMM")
    private BigDecimal comm;
    @JoinColumn(name = "DEPTNO", referencedColumnName = "DEPTNO")
    @ManyToOne
    private Dept deptno;

    public Emp() {
    }

    public Emp(Short empno) {
        this.empno = empno;
    }

    public Short getEmpno() {
        return empno;
    }

    public void setEmpno(Short empno) {
        this.empno = empno;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public Short getMgr() {
        return mgr;
    }

    public void setMgr(Short mgr) {
        this.mgr = mgr;
    }

    public Date getHiredate() {
        return hiredate;
    }

    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }

    public BigDecimal getSal() {
        return sal;
    }

    public void setSal(BigDecimal sal) {
        this.sal = sal;
    }

    public BigDecimal getComm() {
        return comm;
    }

    public void setComm(BigDecimal comm) {
        this.comm = comm;
    }

    public Dept getDeptno() {
        return deptno;
    }

    public void setDeptno(Dept deptno) {
        this.deptno = deptno;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (empno != null ? empno.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Emp)) {
            return false;
        }
        Emp other = (Emp) object;
        if ((this.empno == null && other.empno != null) || (this.empno != null && !this.empno.equals(other.empno))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.model.Emp[empno=" + empno + "]";
    }

}

When we run this project we will get the above mentioned result !!!
Labels: ,

25.Performing Validations and Re-Populating Fields Using MVC

Posted by Sudarsan 0 comments
In this post we are going to learn how to validate data using JSPs and to repopulate the data into the html inputs when the JSP Form page is submitted to the server.

Have look at the fallowing web pages, there we can observe that the data submitted in the form are validated, to perform the validations use the fallowing Servlet and JSP codes.












AddCusServ.java

public class AddCusServ extends HttpServlet {
    @Resource
    private javax.transaction.UserTransaction utx;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            String cname = request.getParameter("cname");
            String uid = request.getParameter("uid");
            String pwd = request.getParameter("pwd");
            String cpwd = request.getParameter("cpwd");
            String dob = request.getParameter("dob");

            boolean error = false;

            if (cname.length() == 0 || cname == null) {
                error = true;
                request.setAttribute("cnameerror", "Please Enter Customer Name");
            } else if (!Validations.isValidName(cname)) {
                error = true;
                request.setAttribute("cnameerror", "Customer Name Can Only Contains Alphabet");
            }

            if (uid.length() == 0 || uid == null) {
                error = true;
                request.setAttribute("uiderror", "Please Enter User Name");
            }

            if (pwd.length() == 0 || pwd == null) {
                error = true;
                request.setAttribute("pwderror", "Please Enter Password");
            }

            if (cpwd.length() == 0 || cpwd == null) {
                error = true;
                request.setAttribute("cpwderror", "Please Confirm Password");
            } else if (!cpwd.equals(pwd)) {
                error = true;
                request.setAttribute("cpwderror", "Passwords do not match ");
            }

            if (dob.length() == 0 || dob == null) {
                error = true;
                request.setAttribute("doberror", "Please Enter Date of Birth");
            } else if (!Validations.isValidDate(dob)) {
                error = true;
                request.setAttribute("doberror", "Date Must be in DD/MM/YYYY Format");
            }

            if (error) {
                RequestDispatcher view = request.getRequestDispatcher("/client/newcustomer.jsp");
                view.forward(request, response);
                return;
            }

            CustLogin custLogin=new CustLogin();
            custLogin.setCustomername(cname);
            custLogin.setUsername(uid);
            custLogin.setPassword(pwd);
            custLogin.setDob(dob);

            Context ctx = (Context) new InitialContext().lookup("java:comp/env");
            utx.begin();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
            em.persist(custLogin);
            utx.commit();

            RequestDispatcher view=request.getRequestDispatcher("/client/index.jsp");
            view.forward(request, response);


        } catch (Exception e) {
            out.print(e.toString());
        } finally {
            out.close();
        }
    }

newcustomer.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
    <head>
        <title>Customer Registration</title>
        <link rel="stylesheet" type="text/css" href="/OnlineTelecomCustomerSupport/css/myStyle.css"/>
    </head>
    <body>
        <h1>Customer Registration</h1>
        <td height="20" align="center">
            <img src="/OnlineTelecomCustomerSupport/images/hr.jpg"/>
        </td>
        <p> <p> <p> 
        <form method="POST" action="<%=request.getContextPath()%>/AddCusServ" class="formContent">
            <table border="0" align="center">
                <tr>
                    <td>Customer Name</td>
 <td><input type="text" name="cname" value="<%=request.getAttribute("cname") != null ? request.getParameter("cname") : request.getParameter("cname") != null ? request.getParameter("cname") : ""%>" /></td>
                    <%if (request.getAttribute("cnameerror") != null) {                    %>
                    <td class="error"><%=request.getAttribute("cnameerror")%></td>
                    <%}%>
                </tr>
                <tr>
                    <td>Desired User Name</td>
                    <td><input type="text" name="uid" value="<%=request.getAttribute("uid") != null ? request.getParameter("uid") : request.getParameter("uid") != null ? request.getParameter("uid") : ""%>" /></td>
                    <%
        if (request.getAttribute("uiderror") != null) {
                    %>
                    <td class="error"><%=request.getAttribute("uiderror")%></td>
                    <%}%>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="password" name="pwd" value="" /></td>
                    <%
        if (request.getAttribute("pwderror") != null) {
                    %>
                    <td class="error"><%=request.getAttribute("pwderror")%></td>
                    <%}%>
                </tr>
                <tr>
                    <td>Confirm Password</td>
                    <td><input type="password" name="cpwd" value="" /></td>
                    <%
        if (request.getAttribute("cpwderror") != null) {
                    %>
                    <td class="error"><%=request.getAttribute("cpwderror")%></td>
                    <%}%>
                </tr>
                <tr>
                    <td>Date of Birth</td>
                    <td><input type="text" name="dob" value="<%=request.getAttribute("dob") != null ? request.getParameter("dob") : request.getParameter("dob") != null ? request.getParameter("dob") : ""%>" /></td>
                    <%
        if (request.getAttribute("doberror") != null) {
                    %>
                    <td class="error"><%=request.getAttribute("doberror")%></td>
                    <%}%>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="Add" class="buttonText" style="background:url(/OnlineTelecomCustomerSupport/images/submit_bg.gif) no-repeat scroll 37px 0px;"/></td>
                    <td></td>
                </tr>
            </table>
        </form> <p> <p> 
        | <a href="/OnlineTelecomCustomerSupport/client/index.jsp">Back</a> |
    </body>
</html>




When we run this project, after successful completion of validations the form data will be submitted to the database otherwise we will get the same page and we need to fulfill the requirements.

Here I am also providing the validating class to validate Name and Date in the JSP page.

Validations.java

public class Validations implements java.io.Serializable {
    public static boolean isValidName(String cname) {
        if (cname.matches("^[a-zA-Z]+$")) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isValidDate(String dob) {
        if (dob.matches("\\d{1,2}/\\d{1,2}/\\d{2,4}")) {
            return true;
        } else {
            return false;
        }
    }
}

Okay Folks !!, Next time I will meet you with some other interesting topic !!!
Labels: ,

24. CRUD Operations Using JPA(Java Perssitance API)

Friday, February 4, 2011 Posted by Sudarsan 2 comments
In this Post we are going to learn the most powerful Database Framework called JPA.

Here I am going to demonstrate CRUD(Create, Retrieve, Update and Delete) operations.

For this create the fallowing directory structure in Netbeans and create the fallowing JSPs and Servlets, and also generate the Entity Class.



index.jsp



view.jsp


addDept.jsp



Now the code for ViewAllServlet.java is given below, and prior to that inject Persistence into the servlet.


public class ViewAllServlet extends HttpServlet {
    @Resource
    private javax.transaction.UserTransaction utx;
   
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            Context ctx = (Context) new InitialContext().lookup("java:comp/env");
            utx.begin();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
            //em.persist(object);
            Query q=em.createNamedQuery("Dept.findAll");
            List list=q.getResultList();
            utx.commit();

            request.setAttribute("list", list);
            RequestDispatcher view=request.getRequestDispatcher("/view.jsp");
            view.forward(request, response);
        } 
        catch(Exception e)
        {
            out.print(e.toString());
        }
        finally {
            out.close();
        }
    } 


Now, the code for DelDeptServlet.java is given below.

public class DelDeptServlet extends HttpServlet {
    @Resource
    private javax.transaction.UserTransaction utx;
   
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {


            String cmd=request.getParameter("cmd");

            if(cmd.equals("Submit"))
            {
                Short deptno=new Short(request.getParameter("deptno"));
                String dname=request.getParameter("dname");
                String loc=request.getParameter("loc");

                Dept dept=new Dept();
                dept.setDeptno(deptno);
                dept.setDname(dname);
                dept.setLoc(loc);

                Context ctx = (Context) new InitialContext().lookup("java:comp/env");
                utx.begin();
                EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
                em.persist(dept);
                utx.commit();

                RequestDispatcher view=request.getRequestDispatcher("/ViewAllServlet");
                view.forward(request, response);

            }


            if(cmd.equals("Delete"))
            {
                String deptno=request.getParameter("deptno");

                Context ctx = (Context) new InitialContext().lookup("java:comp/env");
                utx.begin();
                EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");

                if(deptno!=null)
                {
                    Dept dept=em.find(Dept.class, new Short(deptno));
                    em.remove(dept);
                    utx.commit();
                    RequestDispatcher view=request.getRequestDispatcher("/ViewAllServlet");
                    view.forward(request, response);
                }


                String str[] =request.getParameterValues("del");

                if(str!=null)
                {
                    for(int i=0;i<<str.length;i++)
                    {
                        Dept dept=em.find(Dept.class, new Short(str[i]));
                        em.remove(dept);
                    }
                
                    utx.commit();

                    RequestDispatcher view=request.getRequestDispatcher("/ViewAllServlet");
                    view.forward(request, response);
                }
                else
                {
                    out.print("You Must Select atleast one Record to Delete");
                }
            }

            if(cmd.equals("Edit"))
            {
                Short deptno=new Short(request.getParameter("deptno"));
                Context ctx = (Context) new InitialContext().lookup("java:comp/env");
                utx.begin();
                EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
                Dept dept=em.find(Dept.class, deptno);
                utx.commit();

                request.setAttribute("dept", dept);
                RequestDispatcher view=request.getRequestDispatcher("/addDept.jsp");
                view.forward(request, response);

            }

            if(cmd.equals("Update"))
            {

                Short deptno=new Short(request.getParameter("deptno"));
                String dname=request.getParameter("dname");
                String loc=request.getParameter("loc");
                Context ctx = (Context) new InitialContext().lookup("java:comp/env");
                 utx.begin();
                EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
                Dept dept=em.find(Dept.class, deptno);
                dept.setDname(dname);
                dept.setLoc(loc);
                em.merge(dept);
                utx.commit();

                RequestDispatcher view=request.getRequestDispatcher("/ViewAllServlet");
                view.forward(request, response);
            }
            
        }

        catch(Exception e)
        {
            out.print(e.toString());
        }
        finally {
            out.close();
        }
    } 
When we compile the above program we will get the fallowing output.



That's it folks !!!

I will get back to you with some more interesting topics !!
Labels: ,