0
    package com.jee6.beans;

import com.jee6.entity.Employee;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.*;
import javax.transaction.SystemException;

@ManagedBean
@SessionScoped
public class EmployeeBean {
@PersistenceContext(unitName = "ServicePU")
private EntityManager em;
@Resource
private javax.transaction.UserTransaction utx;
private List<Employee> emplist=new ArrayList<Employee>();
//private Query sql="SELECT e FROM Employee e";
private Employee emp= new Employee();


public Employee getEmp() {
    return emp;
}

public void setEmp(Employee emp) {
    this.emp = emp;
}

public List<Employee> getEmplist() {
    return emplist=findAll();
}

public void setEmplist(List<Employee> emplist) {
    this.emplist = emplist;
}

public List<Employee> findAll(){
    emplist=(List<Employee>)em.createQuery("Select e From Employee e").getResultList();
    return emplist;
}
public EmployeeBean() {
}
public String saveEmployee(){
    persist(emp);
    return null;
}
public String deleteEmployee(Employee e){
   try{
       em.remove(e);
       emplist=findAll();
   } 
       catch (Exception ex)
    {
     Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exceptioncaught", ex);
    }
   return null;
 }
 public void persist(Object object) {
    try {
        utx.begin();
        em.persist(object);
        utx.commit();
    } catch (Exception e) {
      Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
        throw new RuntimeException(e);
    }
}

}

I want to delete data from DataTable in JSF above code only got no output. I am try to fix that code and get no output. Before that I got IllegalException in delete method at (em.remove(e);). Is there anyone who can correct me and appreciate for that.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Kathy Red
  • 1
  • 1

1 Answers1

0

As you're not using EJBs, you have to manually manage all the DB transactions. You need to call begin() and commit() yourself everytime when you perform a DB action on the entity by JPA EntityManager. You are not doing that in the deleteEmployee() method.

Much better would be to move all that JPA works into a @Stateless EJB and inject it in turn as @EJB in your managed bean class. This way you don't need to worry about transactions anymore. For a kickoff example, see also the "update" part of this answer: JSF managed-bean EJB injection.


Unrelated to the concrete problem, your getters should not perform DB actions at all. Your getEmplist() is invoking the DB everytime the method is called. This is unnecessarily expensive. Rather do the job in the bean's @PostConstruct method. See also Why JSF calls getters multiple times.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555