26.Displaying Employees by Department Number Using JPA

Saturday, February 5, 2011 Posted by Sudarsan
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: ,

Post a Comment