In this EJB-JPA tutorial, we will use EntityManager in the Stateless Session Bean. Then, we will implement the bean to learn the persist method of the EntityManager.
Persistence.xml file
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://xmlns.jcp.org/xml/ns/persistence <persistence-unit name="JPASavingsAccount"> <jta-data-source>java:/MSSQLDS</jta-data-source> <class>tube.coding.examples.jpa.entity.SavingsAccount</class> </persistence-unit> </persistence> |
Remote Interface
1 2 3 4 5 6 7 8 9 |
package tube.codingexamples.ejb.statelessbean; import javax.ejb.Remote; @Remote public interface SavingAcBeanRemote { //Sample 3.7: Declare the interface method public int newAccount(String accountHolderName, int initialBalance); } |
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 |
package tube.codingexamples.ejb.statelessbean; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import tube.coding.examples.jpa.entity.SavingsAccount; @Stateless(mappedName = "SavingAcBean") @LocalBean public class SavingAcBean implements SavingAcBeanRemote { //Sample 3.6: Create Entiry Manager //UnitName is from persistance.xml @PersistenceContext(unitName = "JPASavingsAccount") EntityManager em; public SavingAcBean() {} //Sample 3.8: Create New Account public int newAccount(String accountHolderName, int initialBalance) { SavingsAccount account = new SavingsAccount(); account.setBal(initialBalance); account.setpName(accountHolderName); em.persist(account); return account.getPid(); } } |
Categories: JavaEE-EJB-Tube