EJB – Transactions ”; Previous Next A transaction is a single unit of work items, which follows the ACID properties. ACID stands for Atomic, Consistent, Isolated, and Durable. Atomic − If any of the work item fails, the whole unit will be considered failed. Success meant, all items execute successfully. Consistent − A transaction must keep the system in consistent state. Isolated − Each transaction executes independent of any other transaction. Durable − Transaction should survive system failure if it has been executed or committed. EJB Container/Servers are transaction servers and handles transactions context propagation and distributed transactions. Transactions can be managed by the container or by custom code handling in bean”s code. Container Managed Transactions − In this type, the container manages the transaction states. Bean Managed Transactions − In this type, the developer manages the life cycle of transaction states. Container Managed Transactions EJB 3.0 has specified following attributes of transactions, which EJB containers implement − REQUIRED − Indicates that business method has to be executed within transaction, otherwise a new transaction will be started for that method. REQUIRES_NEW − Indicates that a new transaction, is to be started for the business method. SUPPORTS − Indicates that business method will execute as part of transaction. NOT_SUPPORTED − Indicates that business method should not be executed as part of transaction. MANDATORY − Indicates that business method will execute as part of transaction, otherwise exception will be thrown. NEVER − Indicates if business method executes as part of transaction, then an exception will be thrown. Example package com.tutorialspoint.txn.required; import javax.ejb.* @Stateless @TransactionManagement(TransactionManagementType.CONTAINER) public class UserDetailBean implements UserDetailRemote { private UserDetail; @TransactionAttribute(TransactionAttributeType.REQUIRED) public void createUserDetail() { //create user details object } } createUserDetail() business method is made Required using Required annotation. package com.tutorialspoint.txn.required; import javax.ejb.* @Stateless public class UserSessionBean implements UserRemote { private User; @EJB private UserDetailRemote userDetail; public void createUser() { //create user //… //create user details userDetail.createUserDetail(); } } createUser() business method is using createUserDetail(). If exception occurred during createUser() call and User object is not created then UserDetail object will also not be created. Bean Managed Transactions In Bean Managed Transactions, Transactions can be managed by handling exceptions at application level. Following are the key points to be considered − Start − When to start a transaction in a business method. Sucess − Identify success scenario when a transaction is to be committed. Failed − Identify failure scenario when a transaction is to be rollback. Example package com.tutorialspoint.txn.bmt; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.transaction.UserTransaction; @Stateless @TransactionManagement(value=TransactionManagementType.BEAN) public class AccountBean implements AccountBeanLocal { @Resource private UserTransaction userTransaction; public void transferFund(Account fromAccount, double fund , Account toAccount) throws Exception{ try{ userTransaction.begin(); confirmAccountDetail(fromAccount); withdrawAmount(fromAccount,fund); confirmAccountDetail(toAccount); depositAmount(toAccount,fund); userTransaction.commit(); }catch (InvalidAccountException exception) { userTransaction.rollback(); }catch (InsufficientFundException exception) { userTransaction.rollback(); }catch (PaymentException exception) { userTransaction.rollback(); } } private void confirmAccountDetail(Account account) throws InvalidAccountException { } private void withdrawAmount() throws InsufficientFundException { } private void depositAmount() throws PaymentException{ } } In this example, we made use of UserTransaction interface to mark the beginning of transaction using userTransaction.begin() method call. We mark the completion of transaction, by using userTransaction.commit() method and if any exception occured during transaction then we rollback the complete transaction using userTransaction.rollback() method call. Print Page Previous Next Advertisements ”;
Category: ejb
EJB – Interceptors
EJB – Interceptors ”; Previous Next EJB 3.0 provides specification to intercept business methods calls using methods annotated with @AroundInvoke annotation. An interceptor method is called by ejbContainer before business method call it is intercepting. Following is the example signature of an interceptor method @AroundInvoke public Object methodInterceptor(InvocationContext ctx) throws Exception { System.out.println(“*** Intercepting call to LibraryBean method: ” + ctx.getMethod().getName()); return ctx.proceed(); } Interceptor methods can be applied or bound at three levels. Default − Default interceptor is invoked for every bean within deployment.Default interceptor can be applied only via xml (ejb-jar.xml). Class − Class level interceptor is invoked for every method of the bean. Class level interceptor can be applied both by annotation of via xml(ejb-jar.xml). Method− Method level interceptor is invoked for a particular method of the bean. Method level interceptor can be applied both by annotation of via xml(ejb-jar.xml). We are discussing Class level interceptor here. Interceptor Class package com.tutorialspoint.interceptor; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; public class BusinessInterceptor { @AroundInvoke public Object methodInterceptor(InvocationContext ctx) throws Exception { System.out.println(“*** Intercepting call to LibraryBean method: ” + ctx.getMethod().getName()); return ctx.proceed(); } } Remote Interface import javax.ejb.Remote; @Remote public interface LibraryBeanRemote { //add business method declarations } Intercepted Stateless EJB @Interceptors ({BusinessInterceptor.class}) @Stateless public class LibraryBean implements LibraryBeanRemote { //implement business method } Example Application Let us create a test EJB application to test intercepted stateless EJB. Step Description 1 Create a project with a name EjbComponent under a package com.tutorialspoint.interceptor as explained in the EJB – Create Application chapter. You can also use the project created in EJB – Create Application chapter as such for this chapter to understand intercepted EJB concepts. 2 Create LibraryBean.java and LibraryBeanRemote under package com.tutorialspoint.interceptor as explained in the EJB – Create Application chapter. Keep rest of the files unchanged. 3 Clean and Build the application to make sure business logic is working as per the requirements. 4 Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet. 5 Now create the ejb client, a console based application in the same way as explained in the EJB – Create Application chapter under topic Create Client to access EJB. EJBComponent (EJB Module) LibraryBeanRemote.java package com.tutorialspoint.interceptor; import java.util.List; import javax.ejb.Remote; @Remote public interface LibraryBeanRemote { void addBook(String bookName); List getBooks(); } LibraryBean.java package com.tutorialspoint.interceptor; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateless; import javax.interceptor.Interceptors; @Interceptors ({BusinessInterceptor.class}) @Stateless public class LibraryBean implements LibraryBeanRemote { List<String> bookShelf; public LibraryBean() { bookShelf = new ArrayList<String>(); } public void addBook(String bookName) { bookShelf.add(bookName); } public List<String> getBooks() { return bookShelf; } } As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log. JBoss has automatically created a JNDI entry for our session bean − LibraryBean/remote. We will using this lookup string to get remote business object of type − com.tutorialspoint.interceptor.LibraryBeanRemote JBoss Application Server Log Output … 16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibraryBean/remote – EJB3.x Default Remote Business Interface LibraryBean/remote-com.tutorialspoint.interceptor.LibraryBeanRemote – EJB3.x Remote Business Interface 16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryBean,service=EJB3 16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.interceptor.LibraryBeanRemote ejbName: LibraryBean 16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibraryBean/remote – EJB3.x Default Remote Business Interface LibraryBean/remote-com.tutorialspoint.interceptor.LibraryBeanRemote – EJB3.x Remote Business Interface … EJBTester (EJB Client) jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost These properties are used to initialize the InitialContext object of java naming service. InitialContext object will be used to lookup stateless session bean. EJBTester.java package com.tutorialspoint.test; import com.tutorialspoint.stateful.LibraryBeanRemote; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Properties; import javax.naming.InitialContext; import javax.naming.NamingException; public class EJBTester { BufferedReader brConsoleReader = null; Properties props; InitialContext ctx; { props = new Properties(); try { props.load(new FileInputStream(“jndi.properties”)); } catch (IOException ex) { ex.printStackTrace(); } try { ctx = new InitialContext(props); } catch (NamingException ex) { ex.printStackTrace(); } brConsoleReader = new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) { EJBTester ejbTester = new EJBTester(); ejbTester.testInterceptedEjb(); } private void showGUI() { System.out.println(“**********************”); System.out.println(“Welcome to Book Store”); System.out.println(“**********************”); System.out.print(“Options n1. Add Bookn2. Exit nEnter Choice: “); } private void testInterceptedEjb() { try { int choice = 1; LibraryBeanRemote libraryBean = LibraryBeanRemote)ctx.lookup(“LibraryBean/remote”); while (choice != 2) { String bookName; showGUI(); String strChoice = brConsoleReader.readLine(); choice = Integer.parseInt(strChoice); if (choice == 1) { System.out.print(“Enter book name: “); bookName = brConsoleReader.readLine(); Book book = new Book(); book.setName(bookName); libraryBean.addBook(book); } else if (choice == 2) { break; } } List<Book> booksList = libraryBean.getBooks(); System.out.println(“Book(s) entered so far: ” + booksList.size()); int i = 0; for (Book book:booksList) { System.out.println((i+1)+”. ” + book.getName()); i++; } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); }finally { try { if(brConsoleReader !=null) { brConsoleReader.close(); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } } } EJBTester performs the following tasks − Load properties from jndi.properties and initialize the InitialContext object. In testInterceptedEjb() method, jndi lookup is done with the name – “LibraryBean/remote” to obtain the remote business object (stateless EJB). Then user is shown a library store User Interface and he/she is asked to enter a choice. If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is storing the book in its instance variable. If the user enters 2, the system retrieves books using stateless session bean getBooks() method and exits. Run Client to Access EJB Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file. Verify the following output in Netbeans console. run: ********************** Welcome to Book Store ********************** Options 1. Add Book 2. Exit Enter Choice: 1 Enter book name: Learn Java ********************** Welcome to Book Store ********************** Options 1. Add Book 2. Exit Enter Choice: 2 Book(s) entered so far: 1 1. Learn Java BUILD SUCCESSFUL (total time: 13 seconds) JBoss Application Server Log Output Verify the following output in JBoss Application server log output. …. 09:55:40,741 INFO [STDOUT] *** Intercepting call to LibraryBean method: addBook 09:55:43,661 INFO [STDOUT] *** Intercepting call to LibraryBean method: getBooks
EJB – Annotations
EJB – Annotations ”; Previous Next Annotations were introduced in Java 5.0. The purpose of having annotations is to attach additional information in the class or a meta-data of a class within its source code. In EJB 3.0, annotations are used to describe configuration meta-data in EJB classes. By this way, EJB 3.0 eliminates the need to describe configuration data in configuration XML files. EJB container uses compiler tool to generate required artifacts like interfaces, deployment descriptors by reading those annotations. Following is the list of commonly used annotations. Sr.no Name Description 1 javax.ejb.Stateless Specifies that a given EJB class is a stateless session bean. Attributes name − Used to specify name of the session bean. mappedName − Used to specify the JNDI name of the session bean. description − Used to provide description of the session bean. 2 javax.ejb.Stateful Specifies that a given EJB class is a stateful session bean. Attributes name − Used to specify name of the session bean. mappedName − Used to specify the JNDI name of the session bean. description − Used to provide description of the session bean. 3 javax.ejb.MessageDrivenBean Specifies that a given EJB class is a message driven bean. Attributes name − Used to specify name of the message driven bean. messageListenerInterface − Used to specify message listener interface for the message driven bean. activationConfig − Used to specify the configuration details of the message-driven bean in an operational environment of the message driven bean. mappedName − Used to specify the JNDI name of the session bean. description − Used to provide description of the session bean. 4 javax.ejb.EJB Used to specify or inject a dependency as EJB instance into another EJB. Attributes name − Used to specify name, which will be used to locate the referenced bean in the environment. beanInterface − Used to specify the interface type of the referenced bean. beanName − Used to provide name of the referenced bean. mappedName − Used to specify the JNDI name of the referenced bean. description − Used to provide description of the referenced bean. 5 javax.ejb.Local Used to specify Local interface(s) of a session bean. This local interface states the business methods of the session bean (which can be stateless or stateful). This interface is used to expose the business methods to local clients, which are running in the same deployment/application as EJB. Attributes value − Used to specify the list of local interfaces as an array of interfaces. 6 javax.ejb.Remote Used to specify Remote interface(s) of a session bean. This remote interface states the business methods of the session bean (which can be stateless or stateful). This interface is used to expose the business methods to remote clients, which are running in different deployment/application as EJB. Attributes value − Used to specify the list of remote interfaces as an array of interfaces. 7 javax.ejb.Activation ConfigProperty Used to specify properties required for a message driven bean. For example, end point, destination, message selector etc. This annotation is passed as a parameter to activationConfig attribute of javax.ejb.MessageDrivenBean annotation. Attributes propertyName − name of the property. propertyValue − value of the property. 8 javax.ejb.PostActivate Used to specify callback method of EJB lifecycle. This method will be called when EJB container just activated/reactivated the bean instance. This interface is used to expose the business methods to local clients, which are running in same deployment/application as EJB. Print Page Previous Next Advertisements ”;
EJB – JNDI Bindings
EJB – JNDI Bindings ”; Previous Next JNDI stands for Java Naming and Directory Interface. It is a set of API and service interfaces. Java based applications use JNDI for naming and directory services. In context of EJB, there are two terms. Binding − This refers to assigning a name to an EJB object, which can be used later. Lookup − This refers to looking up and getting an object of EJB. In Jboss, session beans are bound in JNDI in the following format by default. local − EJB-name/local remote − EJB-name/remote In case, EJB are bundled with <application-name>.ear file, then default format is as following − local − application-name/ejb-name/local remote − application-name/ejb-name/remote Example of Default Binding Refer to EJB – Create Application chapter”s JBoss console output. JBoss Application Server Log Output … 16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3 16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean 16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibrarySessionBean/remote – EJB3.x Default Remote Business Interface LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote – EJB3.x Remote Business Interface … Customized Binding Following annotations can be used to customize the default JNDI bindings − local − org.jboss.ejb3.LocalBinding remote − org.jboss.ejb3.RemoteBindings Update LibrarySessionBean.java. Refer to EJB – Create Application chapter. LibrarySessionBean package com.tutorialspoint.stateless; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateless; @Stateless @LocalBinding(jndiBinding=”tutorialsPoint/librarySession”) public class LibrarySessionBean implements LibrarySessionBeanLocal { List<String> bookShelf; public LibrarySessionBean() { bookShelf = new ArrayList<String>(); } public void addBook(String bookName) { bookShelf.add(bookName); } public List<String> getBooks() { return bookShelf; } } LibrarySessionBeanLocal package com.tutorialspoint.stateless; import java.util.List; import javax.ejb.Local; @Local public interface LibrarySessionBeanLocal { void addBook(String bookName); List getBooks(); } Build the project, deploy the application on Jboss, and verify the following output in Jboss console − … 16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3 16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean 16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: tutorialsPoint/librarySession – EJB3.x Default Local Business Interface tutorialsPoint/librarySession-com.tutorialspoint.stateless.LibrarySessionBeanLocal – EJB3.x Local Business Interface … Print Page Previous Next Advertisements ”;
EJB – Useful Resources
EJB – Useful Resources ”; Previous Next The following resources contain additional information on EJB. Please use them to get more in-depth knowledge on this. Useful Links on EJB & Java Enterprise JavaBeans Technology − Oracle”s official website on EJB listing down latest specifications, Java Persistence API etc. Wiki page on Enterprise JavaBeans Technology − A short tutorial on Enterprise JavaBeans Technology. JavaTM 2 SDK, Standard Edition − Official site for JavaTM 2 SDK, Standard Edition Free Java Download − Download Java for your desktop computer now! Sun Developer Network − Sun Microsystem”s official website listing down all the API documentation, latest Java Technologies, Books and other resource. Useful Books on EJB & Java To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
EJB – Blobs/Clobs
EJB – Blobs/Clobs ”; Previous Next EJB 3.0 provides support for Blob and Clob types using @Lob annotation. Following java types can be mapped using @Lob annotation. java.sql.Blob java.sql.Clob byte[] String Serializable Object @Entity @Table(name=”books”) @EntityListeners(BookCallbackListener.class) public class Book implements Serializable{ … private byte[] image; @Lob @Basic(fetch= FetchType.EAGER) public byte[] getImage() { return image; } … } Example Application Let us create a test EJB application to test blob/clob support in EJB 3.0. Step Description 1 Create a project with a name EjbComponent under a package com.tutorialspoint.entity as explained in the EJB – Create Application chapter. Please use the project created in EJB – Persistence chapter as such for this chapter to understand clob/blob objects in ejb concepts. 2 Create Book.java under package com.tutorialspoint.entity. Use EJB – Persistence chapter as reference. Keep rest of the files unchanged. 3 Clean and Build the application to make sure business logic is working as per the requirements. 4 Finally, deploy the application in the form of a jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet. 5 Now create the EJB client, a console based application in the same way as explained in the EJB – Create Application chapter under topic Create Client to access EJB. Create/Alter Book Table CREATE TABLE book ( id integer PRIMARY KEY, name varchar(50) ); Alter table book add image bytea; Alter table book add xml text; EJBComponent (EJB Module) Book.java package com.tutorialspoint.entity; import com.tutorialspoint.callback.BookCallbackListener; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; @Entity @Table(name=”book”) public class Book implements Serializable{ private int id; private String name; private byte[] image; private String xml; public Book() { } @Id @GeneratedValue(strategy= GenerationType.IDENTITY) @Column(name=”id”) public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Lob @Basic(fetch= FetchType.EAGER) public byte[] getImage() { return image; } public void setImage(byte[] image) { this.image = image; } @Lob @Basic(fetch= FetchType.EAGER) public String getXml() { return xml; } public void setXml(String xml) { this.xml = xml; } } LibraryPersistentBeanRemote.java package com.tutorialspoint.stateless; import com.tutorialspoint.entity.Book; import java.util.List; import javax.ejb.Remote; @Remote public interface LibraryPersistentBeanRemote { void addBook(Book bookName); List<Book> getBooks(); } LibraryPersistentBean.java package com.tutorialspoint.stateless; import com.tutorialspoint.entity.Book; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless public class LibraryPersistentBean implements LibraryPersistentBeanRemote { public LibraryPersistentBean() { } @PersistenceContext(unitName=”EjbComponentPU”) private EntityManager entityManager; public void addBook(Book book) { entityManager.persist(book); } public List<Book> getBooks() { return entityManager.createQuery(“From Book”).getResultList(); } } As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log. JBoss has automatically created a JNDI entry for our session bean – LibraryPersistentBean/remote. We will using this lookup string to get remote business object of type – com.tutorialspoint.interceptor.LibraryPersistentBeanRemote JBoss Application Server Log Output … 16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibraryPersistentBean/remote – EJB3.x Default Remote Business Interface LibraryPersistentBean/remote-com.tutorialspoint.interceptor.LibraryPersistentBeanRemote – EJB3.x Remote Business Interface 16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBean,service=EJB3 16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.interceptor.LibraryPersistentBeanRemote ejbName: LibraryPersistentBean 16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibraryPersistentBean/remote – EJB3.x Default Remote Business Interface LibraryPersistentBean/remote-com.tutorialspoint.interceptor.LibraryPersistentBeanRemote – EJB3.x Remote Business Interface … EJBTester (EJB Client) jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost These properties are used to initialize the InitialContext object of java naming service. InitialContext object will be used to lookup stateless session bean. EJBTester.java package com.tutorialspoint.test; import com.tutorialspoint.stateful.LibraryBeanRemote; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Properties; import javax.naming.InitialContext; import javax.naming.NamingException; public class EJBTester { BufferedReader brConsoleReader = null; Properties props; InitialContext ctx; { props = new Properties(); try { props.load(new FileInputStream(“jndi.properties”)); } catch (IOException ex) { ex.printStackTrace(); } try { ctx = new InitialContext(props); } catch (NamingException ex) { ex.printStackTrace(); } brConsoleReader = new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) { EJBTester ejbTester = new EJBTester(); ejbTester.testBlobClob(); } private void showGUI() { System.out.println(“**********************”); System.out.println(“Welcome to Book Store”); System.out.println(“**********************”); System.out.print(“Options n1. Add Bookn2. Exit nEnter Choice: “); } private void testBlobClob() { try { int choice = 1; LibraryPersistentBeanRemote libraryBean = (LibraryPersistentBeanRemote) ctx.lookup(“LibraryPersistentBean/remote”); while (choice != 2) { String bookName; String publisherName; String publisherAddress; showGUI(); String strChoice = brConsoleReader.readLine(); choice = Integer.parseInt(strChoice); if (choice == 1) { System.out.print(“Enter book name: “); bookName = brConsoleReader.readLine(); String xml = “<book><name>”+bookName+”</name></book>”; Book book = new Book(); book.setName(bookName); byte[] imageBytes = {0x32, 0x32,0x32, 0x32,0x32, 0x32,0x32, 0x32, 0x32, 0x32,0x32, 0x32,0x32, 0x32,0x32, 0x32, 0x32, 0x32,0x32, 0x32,0x32, 0x32,0x32, 0x32 }; book.setImage(imageBytes); book.setXml(xml); libraryBean.addBook(book); } else if (choice == 2) { break; } } List<Book> booksList = libraryBean.getBooks(); System.out.println(“Book(s) entered so far: ” + booksList.size()); int i = 0; for (Book book:booksList) { System.out.println((i+1)+”. ” + book.getName()); byte[] imageByts = book.getImage(); if(imageByts != null) { System.out.print(“image bytes: [“); for(int j = 0; j < imageByts.length ; j++) { System.out.print(“0x” + String.format(“%x”, imageByts[j]) +” “); } System.out.println(“]”); } System.out.println(book.getXml()); i++; } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); }finally { try { if(brConsoleReader !=null) { brConsoleReader.close(); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } } } EJBTester performs the following tasks. Load properties from jndi.properties and initialize the InitialContext object. In testInterceptedEjb() method, jndi lookup is done with name – “LibraryPersistenceBean/remote” to obtain the remote business object (stateless EJB). Then the user is shown a library store User Interface and he/she is asked to enter a choice. If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is storing the book in database. If the user enters 2, the system retrieves books using stateless session bean getBooks() method and exits. Run Client to Access EJB Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file. Verify the following output in Netbeans console. run: ********************** Welcome to Book Store ********************** Options 1. Add Book 2. Exit Enter Choice: 1 Enter book name: learn testing ********************** Welcome to Book Store ********************** Options 1. Add Book 2. Exit Enter
EJB – Query Language
EJB – Query Language ”; Previous Next EJB Query Language is quite handy to write custom queries without worrying about underlying database details. It is quite similar to HQL, hibernate query language and is often referred by the name EJBQL. To demonstrate EJBQL in EJB, we are going to do the following tasks − Step 1 − Create table in database. Step 2 − Create a stateless EJB having business me. Step 3 −Update stateless EJB. Add methods to add records and get records from database via entity manager. Step 4 − A console based application client will access the stateless EJB to persist data in database. Create Table Create a table books in default database postgres. CREATE TABLE books ( id integer PRIMARY KEY, name varchar(50) ); Create a Model Class public class Book implements Serializable{ private int id; private String name; public Book() { } public int getId() { return id; } … } Create Stateless EJB @Stateless public class LibraryPersistentBean implements LibraryPersistentBeanRemote { public void addBook(Book book) { //persist book using entity manager } public List<Book> getBooks() { //get books using entity manager } … } After building the EJB module, we need a client to access the stateless bean, which we will be going to create in the next section. Example Application Let us create a test EJB application to test EJB database access mechanism. Step Description 1 Create a project with a name EjbComponent under a package com.tutorialspoint.entity as explained in the EJB – Create Application chapter. You can also use the project created in EJB – Create Application chapter as such for this chapter to understand EJB data access concepts. 2 Create Book.java under package com.tutorialspoint.entity and modify it as shown below. 3 Create LibraryPersistentBean.java and LibraryPersistentBeanRemote as explained in the EJB – Create Application chapter and modify them as shown below. 4 Clean and Build the application to make sure business logic is working as per the requirements. 5 Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet. 6 Now create the EJB client, a console based application in the same way as explained in the EJB – Create Application chapter under topic Create Client to access EJB. Modify it as shown below. EJBComponent (EJB Module) Book.java package com.tutorialspoint.entity; import java.io.Serializable; public class Book implements Serializable{ private int id; private String name; public Book() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } LibraryPersistentBeanRemote.java package com.tutorialspoint.stateless; import com.tutorialspoint.entity.Book; import java.util.List; import javax.ejb.Remote; @Remote public interface LibraryPersistentBeanRemote { void addBook(Book bookName); List<Book> getBooks(); } LibraryPersistentBean.java package com.tutorialspoint.stateless; import com.tutorialspoint.entity.Book; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; @Stateless public class LibraryPersistentBean implements LibraryPersistentBeanRemote { public LibraryPersistentBean() { } @PersistenceContext(unitName=”EntityEjbPU”) private EntityManager entityManager; public void addBook(Book book) { entityManager.persist(book); } public List<Book> getBooks() { //create an ejbql expression String ejbQL = “From Book b where b.name like ?1”; //create query Query query = entityManager.createQuery(ejbQL); //substitute parameter. query.setParameter(1, “%test%”); //execute the query return query.getResultList(); } } As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log. JBoss has automatically created a JNDI entry for our session bean − LibraryPersistentBean/remote. We will be using this lookup string to get remote business object of type − com.tutorialspoint.stateless.LibraryPersistentBeanRemote JBoss Application Server Log Output … 16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibraryPersistentBean/remote – EJB3.x Default Remote Business Interface LibraryPersistentBean/remote-com.tutorialspoint.stateless.LibraryPersistentBeanRemote – EJB3.x Remote Business Interface 16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBeanRemote,service=EJB3 16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibraryPersistentBeanRemote ejbName: LibraryPersistentBean 16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibraryPersistentBean/remote – EJB3.x Default Remote Business Interface LibraryPersistentBean/remote-com.tutorialspoint.stateless.LibraryPersistentBeanRemote – EJB3.x Remote Business Interface … EJBTester (EJB Client) jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost These properties are used to initialize the InitialContext object of java naming service. InitialContext object will be used to lookup stateless session bean. EJBTester.java package com.tutorialspoint.test; import com.tutorialspoint.stateless.LibraryPersistentBeanRemote; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Properties; import javax.naming.InitialContext; import javax.naming.NamingException; public class EJBTester { BufferedReader brConsoleReader = null; Properties props; InitialContext ctx; { props = new Properties(); try { props.load(new FileInputStream(“jndi.properties”)); } catch (IOException ex) { ex.printStackTrace(); } try { ctx = new InitialContext(props); } catch (NamingException ex) { ex.printStackTrace(); } brConsoleReader = new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) { EJBTester ejbTester = new EJBTester(); ejbTester.testEntityEjb(); } private void showGUI() { System.out.println(“**********************”); System.out.println(“Welcome to Book Store”); System.out.println(“**********************”); System.out.print(“Options n1. Add Bookn2. Exit nEnter Choice: “); } private void testEntityEjb() { try { int choice = 1; LibraryPersistentBeanRemote libraryBean = LibraryPersistentBeanRemote) ctx.lookup(“LibraryPersistentBean/remote”); while (choice != 2) { String bookName; showGUI(); String strChoice = brConsoleReader.readLine(); choice = Integer.parseInt(strChoice); if (choice == 1) { System.out.print(“Enter book name: “); bookName = brConsoleReader.readLine(); Book book = new Book(); book.setName(bookName); libraryBean.addBook(book); } else if (choice == 2) { break; } } List<Book> booksList = libraryBean.getBooks(); System.out.println(“Book(s) entered so far: ” + booksList.size()); int i = 0; for (Book book:booksList) { System.out.println((i+1)+”. ” + book.getName()); i++; } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); }finally { try { if(brConsoleReader !=null) { brConsoleReader.close(); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } } } EJBTester performs the following tasks − Load properties from jndi.properties and initialize the InitialContext object. In testStatefulEjb() method, jndi lookup is done with the name – “LibraryStatelessSessionBean/remote” to obtain the remote business object (stateful ejb). Then user is shown a library store User Interface and he/she is asked to enter a choice. If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is persisting the book in database via EntityManager call. If the user enters 2, the system retrieves books using stateless session bean getBooks() method and exits. Then another jndi lookup is done with name – “LibraryStatelessSessionBean/remote”
EJB – Stateful Bean
EJB – Stateful Bean ”; Previous Next A stateful session bean is a type of enterprise bean, which preserve the conversational state with client. A stateful session bean as per its name keeps associated client state in its instance variables. EJB Container creates a separate stateful session bean to process client”s each request. As soon as request scope is over, statelful session bean is destroyed. Steps to Create Stateful EJB Following are the steps required to create a stateful EJB − Create a remote/local interface exposing the business methods. This interface will be used by the EJB client application. Use @Local annotation if EJB client is in same environment where EJB session bean need to be deployed. Use @Remote annotation if EJB client is in different environment where EJB session bean need to be deployed. Create a stateful session bean, implementing the above interface. Use @Stateful annotation to signify it a stateful bean. EJB Container automatically creates the relevant configurations or interfaces required by reading this annotation during deployment. Remote Interface import javax.ejb.Remote; @Remote public interface LibraryStatefulSessionBeanRemote { //add business method declarations } Stateful EJB @Stateful public class LibraryStatefulSessionBean implements LibraryStatefulSessionBeanRemote { //implement business method } Example Application Let us create a test EJB application to test stateful EJB. Step Description 1 Create a project with a name EjbComponent under a package com.tutorialspoint.stateful as explained in the EJB − Create Application chapter. You can also use the project created in EJB – Create Application chapter as such for this chapter to understand stateful EJB concepts. 2 Create LibraryStatefulSessionBean.java and LibraryStatefulSessionBeanRemote as explained in the EJB − Create Application chapter. Keep rest of the files unchanged. 3 Clean and Build the application to make sure business logic is working as per the requirements. 4 Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet. 5 Now create the EJB client, a console based application in the same way as explained in the EJB – Create Application chapter under topic Create Client to access EJB. EJBComponent (EJB Module) LibraryStatefulSessionBeanRemote.java package com.tutorialspoint.stateful; import java.util.List; import javax.ejb.Remote; @Remote public interface LibraryStatefulSessionBeanRemote { void addBook(String bookName); List getBooks(); } LibraryStatefulSessionBean.java package com.tutorialspoint.stateful; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateful; @Stateful public class LibraryStatefulSessionBean implements LibraryStatefulSessionBeanRemote { List<String> bookShelf; public LibraryStatefulSessionBean() { bookShelf = new ArrayList<String>(); } public void addBook(String bookName) { bookShelf.add(bookName); } public List<String> getBooks() { return bookShelf; } } As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log. JBoss has automatically created a JNDI entry for our session bean − LibraryStatefulSessionBean/remote. We will be using this lookup string to get remote business object of type − com.tutorialspoint.stateful.LibraryStatefulSessionBeanRemote JBoss Application Server Log Output … 16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibraryStatefulSessionBean/remote – EJB3.x Default Remote Business Interface LibraryStatefulSessionBean/remote-com.tutorialspoint.stateful.LibraryStatefulSessionBeanRemote – EJB3.x Remote Business Interface 16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryStatefulSessionBean,service=EJB3 16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateful.LibraryStatefulSessionBeanRemote ejbName: LibraryStatefulSessionBean 16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibraryStatefulSessionBean/remote – EJB3.x Default Remote Business Interface LibraryStatefulSessionBean/remote-com.tutorialspoint.stateful.LibraryStatefulSessionBeanRemote – EJB3.x Remote Business Interface … EJBTester (EJB Client) jndi.properties java.naming.factory.initial = org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs = org.jboss.naming:org.jnp.interfaces java.naming.provider.url = localhost These properties are used to initialize the InitialContext object of java naming service. InitialContext object will be used to lookup stateful session bean. EJBTester.java package com.tutorialspoint.test; import com.tutorialspoint.stateful.LibraryStatefulSessionBeanRemote; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Properties; import javax.naming.InitialContext; import javax.naming.NamingException; public class EJBTester { BufferedReader brConsoleReader = null; Properties props; InitialContext ctx; { props = new Properties(); try { props.load(new FileInputStream(“jndi.properties”)); } catch (IOException ex) { ex.printStackTrace(); } try { ctx = new InitialContext(props); } catch (NamingException ex) { ex.printStackTrace(); } brConsoleReader = new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) { EJBTester ejbTester = new EJBTester(); ejbTester.testStatelessEjb(); } private void showGUI() { System.out.println(“**********************”); System.out.println(“Welcome to Book Store”); System.out.println(“**********************”); System.out.print(“Options n1. Add Bookn2. Exit nEnter Choice: “); } private void testStatelessEjb() { try { int choice = 1; LibraryStatefulSessionBeanRemote libraryBean = LibraryStatefulSessionBeanRemote)ctx.lookup(“LibraryStatefulSessionBean/remote”); while (choice != 2) { String bookName; showGUI(); String strChoice = brConsoleReader.readLine(); choice = Integer.parseInt(strChoice); if (choice == 1) { System.out.print(“Enter book name: “); bookName = brConsoleReader.readLine(); Book book = new Book(); book.setName(bookName); libraryBean.addBook(book); } else if (choice == 2) { break; } } List<Book> booksList = libraryBean.getBooks(); System.out.println(“Book(s) entered so far: ” + booksList.size()); int i = 0; for (Book book:booksList) { System.out.println((i+1)+”. ” + book.getName()); i++; } LibraryStatefulSessionBeanRemote libraryBean1 = (LibraryStatefulSessionBeanRemote)ctx.lookup(“LibraryStatefulSessionBean/remote”); List<String> booksList1 = libraryBean1.getBooks(); System.out.println( “***Using second lookup to get library stateful object***”); System.out.println( “Book(s) entered so far: ” + booksList1.size()); for (int i = 0; i < booksList1.size(); ++i) { System.out.println((i+1)+”. ” + booksList1.get(i)); } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); }finally { try { if(brConsoleReader !=null) { brConsoleReader.close(); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } } } EJBTester performs the following tasks − Load properties from jndi.properties and initialize the InitialContext object. In testStatefulEjb() method, jndi lookup is done with name – “LibraryStatefulSessionBean/remote” to obtain the remote business object (stateful ejb). Then the user is shown a library store User Interface and he/she is asked to enter a choice. If user enters 1, system asks for book name and saves the book using stateful session bean addBook() method. Session Bean is storing the book in its instance variable. If user enters 2, system retrieves books using stateful session bean getBooks() method and exits. Then another jndi lookup is done with the name – “LibraryStatefulSessionBean/remote” to obtain the remote business object (stateful EJB) again and listing of books is done. Run Client to Access EJB Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file. Verify the following output in Netbeans console − run: ********************** Welcome to Book Store ********************** Options 1. Add Book 2. Exit Enter Choice: 1 Enter book name: Learn Java ********************** Welcome to Book Store ********************** Options 1. Add Book 2. Exit Enter Choice: 2 Book(s) entered so far: 1
EJB – Dependency Injection
EJB – Dependency Injection ”; Previous Next EJB 3.0 specification provides annotations, which can be applied on fields or setter methods to inject dependencies. EJB Container uses the global JNDI registry to locate the dependency. Following annotations are used in EJB 3.0 for dependency injection. @EJB − used to inject other EJB reference. @Resource − used to inject datasource or singleton services like sessionContext, timerService etc. Steps to Use @EJB @EJB can be used on fields or on methods in the following manner − public class LibraryMessageBean implements MessageListener { //dependency injection on field. @EJB LibraryPersistentBeanRemote libraryBean; … } public class LibraryMessageBean implements MessageListener { LibraryPersistentBeanRemote libraryBean; //dependency injection on method. @EJB(beanName=”com.tutorialspoint.stateless.LibraryPersistentBean”) public void setLibraryPersistentBean( LibraryPersistentBeanRemote libraryBean) { this.libraryBean = libraryBean; } … } Steps to use @Resource @Resource is normally used to inject EJB Container provided singletons. public class LibraryMessageBean implements MessageListener { @Resource private MessageDrivenContext mdctx; … } Example Application Let us create a test EJB application to test Dependency Injection Service in EJB. Step Description 1 Create a project with a name EjbComponent under a package com.tutorialspoint.timer as explained in the EJB – Create Application chapter. 2 Use Beans created in the EJB – Message Driven Bean chapter. Keep rest of the files unchanged. 3 Clean and Build the application to make sure business logic is working as per the requirements. 4 Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet. 5 Now create the EJB client, a console based application in the same way as explained in the EJB – Create Application chapter under topic Create Client to access EJB. EJBComponent (EJB Module) LibraryMessageBean.java package com.tuturialspoint.messagebean; import com.tutorialspoint.entity.Book; import com.tutorialspoint.stateless.LibraryPersistentBeanRemote; import javax.annotation.Resource; import javax.ejb.ActivationConfigProperty; import javax.ejb.EJB; import javax.ejb.MessageDriven; import javax.ejb.MessageDrivenContext; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.ObjectMessage; @MessageDriven( name = “BookMessageHandler”, activationConfig = { @ActivationConfigProperty( propertyName = “destinationType”, propertyValue = “javax.jms.Queue”), @ActivationConfigProperty( propertyName = “destination”, propertyValue =”/queue/BookQueue”) } ) public class LibraryMessageBean implements MessageListener { @Resource private MessageDrivenContext mdctx; @EJB LibraryPersistentBeanRemote libraryBean; public LibraryMessageBean() { } public void onMessage(Message message) { ObjectMessage objectMessage = null; try { objectMessage = (ObjectMessage) message; Book book = (Book) objectMessage.getObject(); libraryBean.addBook(book); }catch (JMSException ex) { mdctx.setRollbackOnly(); } } } EJBTester (EJB Client) EJBTester.java package com.tutorialspoint.test; import com.tutorialspoint.entity.Book; import com.tutorialspoint.stateless.LibraryPersistentBeanRemote; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Properties; import javax.jms.ObjectMessage; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; import javax.jms.QueueSender; import javax.jms.QueueSession; import javax.naming.InitialContext; import javax.naming.NamingException; public class EJBTester { BufferedReader brConsoleReader = null; Properties props; InitialContext ctx; { props = new Properties(); try { props.load(new FileInputStream(“jndi.properties”)); } catch (IOException ex) { ex.printStackTrace(); } try { ctx = new InitialContext(props); } catch (NamingException ex) { ex.printStackTrace(); } brConsoleReader = new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) { EJBTester ejbTester = new EJBTester(); ejbTester.testMessageBeanEjb(); } private void showGUI() { System.out.println(“**********************”); System.out.println(“Welcome to Book Store”); System.out.println(“**********************”); System.out.print(“Options n1. Add Bookn2. Exit nEnter Choice: “); } private void testMessageBeanEjb() { try { int choice = 1; Queue queue = (Queue) ctx.lookup(“/queue/BookQueue”); QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup(“ConnectionFactory”); QueueConnection connection = factory.createQueueConnection(); QueueSession session = connection.createQueueSession( false, QueueSession.AUTO_ACKNOWLEDGE); QueueSender sender = session.createSender(queue); while (choice != 2) { String bookName; showGUI(); String strChoice = brConsoleReader.readLine(); choice = Integer.parseInt(strChoice); if (choice == 1) { System.out.print(“Enter book name: “); bookName = brConsoleReader.readLine(); Book book = new Book(); book.setName(bookName); ObjectMessage objectMessage = session.createObjectMessage(book); sender.send(objectMessage); } else if (choice == 2) { break; } } LibraryPersistentBeanRemote libraryBean = (LibraryPersistentBeanRemote) ctx.lookup(“LibraryPersistentBean/remote”); List<Book> booksList = libraryBean.getBooks(); System.out.println(“Book(s) entered so far: ” + booksList.size()); int i = 0; for (Book book:booksList) { System.out.println((i+1)+”. ” + book.getName()); i++; } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); }finally { try { if(brConsoleReader !=null) { brConsoleReader.close(); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } } } EJBTester performs the following tasks − Load properties from jndi.properties and initialize the InitialContext object. In testStatefulEjb() method, jndi lookup is done with the name – “/queue/BookQueue” to obtain reference of queue available in Jboss. Then sender is created using queue session. Then the user is shown a library store User Interface and he/she is asked to enter a choice. If the user enters 1, the system asks for book name and sender sends the book name to queue. When JBoss container receives this message in queue, it calls our message driven bean”s onMessage method. Our message driven bean then saves book using stateful session bean addBook() method. Session Bean is persisting the book in database via EntityManager call. If the user enters 2, then another jndi lookup is done with the name – “LibraryStatefulSessionBean/remote” to obtain the remote business object (stateful EJB) again and listing of books is done. Run Client to Access EJB Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file. Verify the following output in Netbeans console. run: ********************** Welcome to Book Store ********************** Options 1. Add Book 2. Exit Enter Choice: 1 Enter book name: Learn EJB ********************** Welcome to Book Store ********************** Options 1. Add Book 2. Exit Enter Choice: 2 Book(s) entered so far: 2 1. learn java 1. learn EJB BUILD SUCCESSFUL (total time: 15 seconds) The output shown above states that our Message driven bean is receiving the message and storing book in persistent storage and books are retrieved from database. Our message driven bean is using LibraryPersistentBean injected into it using @EJB annotation and in case of exception, MessageDrivenContext, object is used to rollback the transaction. Print Page Previous Next Advertisements ”;
EJB – Discussion
Discuss EJB ”; Previous Next Enterprise Java Beans (EJB) is a development architecture for building highly scalable and robust enterprise level applications to be deployed on J2EE compliant Application Server such as JBOSS, Web Logic etc. EJB 3.0 is being a great shift from EJB 2.0 and makes development of EJB based applications quite easy. This tutorial is developed to provide a comprehensive understanding about the EJB concepts helpful to create and deploy an enterprise level application up and running. Print Page Previous Next Advertisements ”;