Sunday, April 1, 2012

How to create dependent LOV in adf with EJB as business component

Hi,

In this post i will explain you how to create the dependent LOV  in adf where we have EJB as business component.

Pre-Requirement :
   1-Software :jdeveloper 11.1.1.4  IDE
   2-knowledge:basic knowledge of EJB 3.0 ,ADF faces and java

Step 1:create the new project  ,select the java EE application .
Step 2:In model layer (project )create the Entity  from table
Step3:Create the Entity of the Employees and Departments table.
Step4:Add one new named query in the Employee Entity Class
         Employee class code is following




package com.prateek.oracle.adf.model.entity;

import java.io.Serializable;

import java.sql.Timestamp;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@NamedQueries( { @NamedQuery(name = "findAllEmployee",
                             query = "select o from Employee o"),
                 @NamedQuery(name = "findEmployeeById",
                             query = "select o from Employee o where o.employeeId=:empId") })
@Table(name = "EMPLOYEES")
public class Employee implements Serializable {
    @Column(name = "COMMISSION_PCT")
    private Double commissionPct;
    @Column(nullable = false, unique = true, length = 25)
    private String email;
    @Id
    @Column(name = "EMPLOYEE_ID", nullable = false)
    private Long employeeId;
    @Column(name = "FIRST_NAME", length = 20)
    private String firstName;
    @Column(name = "HIRE_DATE", nullable = false)
    private Timestamp hireDate;
    @Column(name = "JOB_ID", nullable = false, length = 10)
    private String jobId;
    @Column(name = "LAST_NAME", nullable = false, length = 25)
    private String lastName;
    @Column(name = "PHONE_NUMBER", length = 20)
    private String phoneNumber;
    private Double salary;
    @ManyToOne
    @JoinColumn(name = "MANAGER_ID")
    private Employee employee;
    @OneToMany(mappedBy = "employee")
    private List<Employee> employeeList;
    @OneToMany(mappedBy = "employee")
    private List<Department> departmentList;
    @ManyToOne
    @JoinColumn(name = "DEPARTMENT_ID")
    private Department department;

    public Employee() {
    }

    public Employee(Double commissionPct, Department department, String email,
                    Long employeeId, String firstName, Timestamp hireDate,
                    String jobId, String lastName, Employee employee,
                    String phoneNumber, Double salary) {
        this.commissionPct = commissionPct;
        this.department = department;
        this.email = email;
        this.employeeId = employeeId;
        this.firstName = firstName;
        this.hireDate = hireDate;
        this.jobId = jobId;
        this.lastName = lastName;
        this.employee = employee;
        this.phoneNumber = phoneNumber;
        this.salary = salary;
    }

    public Double getCommissionPct() {
        return commissionPct;
    }

    public void setCommissionPct(Double commissionPct) {
        this.commissionPct = commissionPct;
    }


    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Long getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(Long employeeId) {
        this.employeeId = employeeId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public Timestamp getHireDate() {
        return hireDate;
    }

    public void setHireDate(Timestamp hireDate) {
        this.hireDate = hireDate;
    }

    public String getJobId() {
        return jobId;
    }

    public void setJobId(String jobId) {
        this.jobId = jobId;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }


    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    public List<Employee> getEmployeeList() {
        return employeeList;
    }

    public void setEmployeeList(List<Employee> employeeList) {
        this.employeeList = employeeList;
    }

    public Employee addEmployee(Employee employee) {
        getEmployeeList().add(employee);
        employee.setEmployee(this);
        return employee;
    }

    public Employee removeEmployee(Employee employee) {
        getEmployeeList().remove(employee);
        employee.setEmployee(null);
        return employee;
    }

    public List<Department> getDepartmentList() {
        return departmentList;
    }

    public void setDepartmentList(List<Department> departmentList) {
        this.departmentList = departmentList;
    }

    public Department addDepartment(Department department) {
        getDepartmentList().add(department);
        department.setEmployee(this);
        return department;
    }

    public Department removeDepartment(Department department) {
        getDepartmentList().remove(department);
        department.setEmployee(null);
        return department;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public String toString() {
        return employeeId + firstName + lastName;
    }
}

Department Entity class is following


package com.prateek.oracle.adf.model.entity;

import java.io.Serializable;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@NamedQueries({
@NamedQuery(name = "Department.findAll", query = "select o from Department o")
})
@Table(name = "DEPARTMENTS")
public class Department implements Serializable {
@Id
@Column(name="DEPARTMENT_ID", nullable = false)
private Long departmentId;
@Column(name="DEPARTMENT_NAME", nullable = false, length = 30)
private String departmentName;
@Column(name="LOCATION_ID")
private Long locationId;
@ManyToOne
@JoinColumn(name = "MANAGER_ID")
private Employee employee;
@OneToMany(mappedBy = "department")
private List employeeList;

public Department() {
}

public Department(Long departmentId, String departmentName,
Long locationId, Employee employee) {
this.departmentId = departmentId;
this.departmentName = departmentName;
this.locationId = locationId;
this.employee = employee;
}

public Long getDepartmentId() {
return departmentId;
}

public void setDepartmentId(Long departmentId) {
this.departmentId = departmentId;
}

public String getDepartmentName() {
return departmentName;
}

public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}

public Long getLocationId() {
return locationId;
}

public void setLocationId(Long locationId) {
this.locationId = locationId;
}


public Employee getEmployee() {
return employee;
}

public void setEmployee(Employee employee) {
this.employee = employee;
}

public List getEmployeeList() {
return employeeList;
}

public void setEmployeeList(List employeeList) {
this.employeeList = employeeList;
}

public Employee addEmployee(Employee employee) {
getEmployeeList().add(employee);
employee.setDepartment(this);
return employee;
}

public Employee removeEmployee(Employee employee) {
getEmployeeList().remove(employee);
employee.setDepartment(null);
return employee;
}

public String toString() {
return departmentId +departmentName ;
}
}


Step5:Create the Session Bean and add all the method  both Entity class
Step6:Code will as following


package com.prateek.oracle.adf.sessionbean;

import com.prateek.oracle.adf.model.entity.Department;

import com.prateek.oracle.adf.model.entity.Employee;

import java.util.List;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless(name = "SessionEJB", mappedName = "DependentLOVINEJB-Model-SessionEJB")
public class SessionEJBBean implements SessionEJB, SessionEJBLocal {
    @PersistenceContext(unitName="Model")
    private EntityManager em;

    public SessionEJBBean() {
    }

    public Object queryByRange(String jpqlStmt, int firstResult,
                               int maxResults) {
        Query query = em.createQuery(jpqlStmt);
        if (firstResult > 0) {
            query = query.setFirstResult(firstResult);
        }
        if (maxResults > 0) {
            query = query.setMaxResults(maxResults);
        }
        return query.getResultList();
    }

    public Department persistDepartment(Department department) {
        em.persist(department);
        return department;
    }

    public Department mergeDepartment(Department department) {
        return em.merge(department);
    }

    public void removeDepartment(Department department) {
        department = em.find(Department.class, department.getDepartmentId());
        em.remove(department);
    }

    /** <code>select o from Department o</code> */
    public List<Department> getDepartmentFindAll() {
        return em.createNamedQuery("Department.findAll").getResultList();
    }

    public Employee persistEmployee(Employee employee) {
        em.persist(employee);
        return employee;
    }

    public Employee mergeEmployee(Employee employee) {
        return em.merge(employee);
    }

    public void removeEmployee(Employee employee) {
        employee = em.find(Employee.class, employee.getEmployeeId());
        em.remove(employee);
    }

    /** <code>select o from Employee o</code> */
    public List<Employee> getEmployeeFindAll() {
        return em.createNamedQuery("Employee.findAll").getResultList();
    }

    /** <code>select o from Employee o</code> */
    public List<Employee> findAllEmployee() {
        return em.createNamedQuery("findAllEmployee").getResultList();
    }

    /** <code>select o from Employee o where o.employeeId=:empId</code> */
    public List<Employee> findEmployeeById(Long empId) {
        return em.createNamedQuery("findEmployeeById").setParameter("empId", empId).getResultList();
    }
}

findAllEmployee and findEmployeeById method i am going to use in jspx page to create the select one choice of Employee and Department Entity.

Step 7:create the backing bean which contains following code :



package com.prateek.oracle.adf.view.backingbean;

import com.prateek.oracle.adf.model.entity.Department;

import com.prateek.oracle.adf.model.entity.Employee;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.view.rich.context.AdfFacesContext;

import oracle.binding.OperationBinding;

public class ExampleBean {
    //it is used to create the select one chioce of the employee
    private List<SelectItem> employeeList;
    //it is used to create the select one choice of the department
    private List<SelectItem> departmentList;
    //employee id will hold the select employee id in jspx page
    private Long employeeId;
    //department id will hold the select department id in jspx page.
    private Long departmentId;


    public void setEmployeeList(List<SelectItem> employeeList) {
        this.employeeList = employeeList;
    }

    public List<SelectItem> getEmployeeList() {
        if (employeeList == null) {
            FacesContext context = FacesContext.getCurrentInstance();
            Application app = context.getApplication();
            DCBindingContainer bindings =
                (DCBindingContainer)app.getVariableResolver().resolveVariable(context,
                                                                              "bindings");
            List<Employee> employee = new ArrayList<Employee>();
            OperationBinding operationBinding =
                bindings.getOperationBinding("findAllEmployee");
            employee = (List<Employee>)operationBinding.execute();
            if (operationBinding.getErrors().isEmpty()) {
                employeeList = new ArrayList<SelectItem>();
                for (Employee employeeValue : employee) {
                    employeeList.add(new SelectItem(employeeValue.getEmployeeId(),
                                                    employeeValue.toString()));
                }
            }
        }
        return employeeList;
    }

    public void setEmployeeId(Long employeeId) {
        this.employeeId = employeeId;
    }

    public Long getEmployeeId() {
        return employeeId;
    }


    public void setDepartmentList(List<SelectItem> departmentList) {
        this.departmentList = departmentList;
    }

        public List<SelectItem> getDepartmentList() {
        if (employeeId != null) {
            Department departmentNew =null;
            FacesContext context = FacesContext.getCurrentInstance();
            Application app = context.getApplication();
            DCBindingContainer bindings =
                (DCBindingContainer)app.getVariableResolver().resolveVariable(context,
                                                                              "bindings");
            List<Employee> employee = new ArrayList<Employee>();

            AdfFacesContext.getCurrentInstance().getPageFlowScope().put("empId",
                                                                        employeeId);
            OperationBinding operationBinding =
                bindings.getOperationBinding("findEmployeeById");
            employee = (List<Employee>)operationBinding.execute();
            Employee exam = employee.get(0);
            departmentNew = exam.getDepartment();
            if (operationBinding.getErrors().isEmpty()) {
                departmentList = new ArrayList<SelectItem>();
                    departmentList.add(new SelectItem(departmentNew.getDepartmentId(),
                                                      departmentNew.toString()));
            }
        }
        return departmentList;
    }

    public void employeeList(ValueChangeEvent valueChangeEvent) {

    }

    public void setDepartmentId(Long departmentId) {
        this.departmentId = departmentId;
    }

    public Long getDepartmentId() {
        return departmentId;
    }
}

Step 8:Create the jspx page which contains the following code



<?xml version='1.0' encoding='UTF-8'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
          xmlns:f="http://java.sun.com/jsf/core"
          xmlns:h="http://java.sun.com/jsf/html"
          xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
  <jsp:directive.page contentType="text/html;charset=UTF-8"/>
  <f:view>
    <af:document id="d1">
      <af:form id="f1">
      <af:selectOneChoice  id="se1" value="#{viewScope.exampleBean.employeeId}" label="Empolyee List"
                         autoSubmit="true" valueChangeListener="#{viewScope.exampleBean.employeeList}">
      <f:selectItems value="#{viewScope.exampleBean.employeeList}" id="tr1"></f:selectItems>
      </af:selectOneChoice>
      <af:selectOneChoice  id="se2" value="#{viewScope.exampleBean.departmentId}" label="Department List" partialTriggers="se1"
                         autoSubmit="true" >
      <f:selectItems value="#{viewScope.exampleBean.departmentList}" id="tr2"></f:selectItems>
      </af:selectOneChoice>
     
      </af:form>
    </af:document>
  </f:view>
</jsp:root>

Step 9:we are creating the jspx manually.means right now we do not have any page def page for this page.just right click the page and click on go to page def file.it will be automatically created the page  def file .




Step 10:add this two method in the page def file because in backing bean we are using this method which are
   1-findAllEmployee
   2-findEmployeeById

Step 11:Also do not forget to add the Backing bean into the adfc-config.xml in view scope.


I know what ever i have written in this post that is not enough to understand the whole logic but believe  me i do not have enough time to explain in depth.


Please open the link to download the example application

http://www.4shared.com/rar/AS9i31ak/DependentLOVINEJB.html

Thanks






No comments:

Post a Comment

Post a Comment