Hi Bill, here is the detail code about my problem.
@Stateless
public class EmployeeFacadeBean implements EmployeeFacade{
@PersistenceContext
private EntityManager manager;
public void createDepartment(
String deptName){
Department department = new Department();
department.setName(deptName);
manager.persist(department);
}
...
....
}
@Entity(name="DEPARTMENT")
@EntityListener(EmployeeListener.class)
@Table(name = "DEPARTMENTS")
public class Department implements java.io.Serializable{
private Long id;
private String lsName;
private Collection<Employee> lEmployees;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId(){
return id;
}
public void setId(Long id){
this.id = id;
}
@Column(name = "NAME")
public String getName(){
return lsName;
}
public void setName(String asName){
this.lsName = asName;
}
@OneToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
public Collection<Employee> getEmployees(){
return lEmployees;
}
public void setEmployees(Collection<Employee> aEmployees){
this.lEmployees = aEmployees;
}
public void addEmployee(String asName,int aiAge, String asSex){
if(lEmployees== null)lEmployees = new ArrayList<Employee>();
Employee lEmployee = new Employee();
lEmployee.setName(asName);
lEmployee.setAge(aiAge);
lEmployee.setSex(asSex);
lEmployee.setDepartment(this);
lEmployees.add(lEmployee);
setEmployees(lEmployees);
}
}
public class EmployeeListener {
@PostPersist
public void insertLog() {
@PersistenceContext
private EntityManager manager;
Log log = new Log();
log.setName("test");
log.setDescription("Employee Add");
manager.persist(log);
}
...
...
}
Now, whenever i add a record into an employee database, i want to add a record in even Log database table also. so i thought to implement in postPersist callback method. But it is not allowing me to create the entitymanager in call back methods. So how do i perform this operation.
Otherwise, can i use java.sql.Connection object to perform my desired operation instead of relying on the Entities. see the code with java.sql.Connection.
@PrePersist
public void insertLog() {
Statement st = con.createStatement();
String sqlStr = "INSERT INTO LOG VALUES(
test,Employee Added)";
st.executeUpdate(sqlStr);
st.close();
con.close();
}
Am i donig anything wrong in callback method implementation to solve my problem? How far it is a vioable solution of using connection object in the callback methods to update the data into other entities?
Pls suggest how to solve this problem. Thanks in advance.