In this EJB-JPA Tuorial, we will implement bean layer on ManyToOne side of the Entity.
Remote Interface
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package tube.codingexamples.ejb.statelessbean; import java.util.List; import javax.ejb.Remote; import tube.coding.examples.jpa.entity.Employee; import tube.coding.examples.jpa.entity.Job; @Remote public interface EmpJobBeanRemote { //Sample 8.08: Bean Method to add Employee public Employee addEmployee(String FName, String MName, String LName, int jobLevel, int jobid); public List<Job> queryJobs(); } |
Bean Implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
package tube.codingexamples.ejb.statelessbean; import java.util.List; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import tube.coding.examples.jpa.entity.Employee; import tube.coding.examples.jpa.entity.Job; @Stateless(mappedName = "EmpJobBean") @LocalBean public class EmpJobBean implements EmpJobBeanRemote { //Sample 8.09: Create Entiry Manager, UnitName is from persistance.xml @PersistenceContext(unitName = "JPASavingsAccount") EntityManager em; public EmpJobBean() { } //Sample 8.10: Implement the Add Employee Method public Employee addEmployee(String FName, String MName, String LName, int jobLevel, int jobid) { //8.10.1: Create Employee Instance Employee emp = new Employee(); emp.setFirstName(FName); emp.setMidName(MName); emp.setLastName(LName); emp.setJobLevel(jobLevel); //8.10.2: Generate EmpId and Set it String id = "PMA42628M"; Integer num = (int) (Math.random() * 100000); id = id.replace("42628", num.toString()); emp.setId(id); //8.10.3: Hook the Job to Employee. EM will take care of the relation Job jobToLink = em.find(Job.class, jobid); emp.setJob(jobToLink); em.persist(emp); return emp; } //Sample 8.11: Implement query jobs public List<Job> queryJobs() { String JpaSql = "Select J from Job J "; Query query = em.createQuery(JpaSql); List<Job> jobs = (List<Job>) query.getResultList(); return jobs; } } |
Categories: JavaEE-EJB-Tube