Tutorial : Hello EJB3

by toy

After I wrote this article http://www.noppanit.com/?p=90. It’s about EJB2. I wrote it from scratch. So, this article I will be writing about EJB3 and I will write it from scratch as well. To compare??EJB3 with EJB2, I found that EJB3 is a lot more comfortable, but it can’t beat Grails anyway. ^_^. So, let gets start.

First, create a project.

??It will look like this

Create an interface like this

Insert this code inside the interface
@Remote <– It’s an annotation for telling J2EE container that this is RemoteInterface

CODE JAVA
package com.noppanit.ejb.interfaces;
import javax.ejb.Remote;
@Remote
public interface MyBeanFacade {
???????????????????? public String sayHello(String name);
}

Insert this code for MyBean.java
@Stateless <– is for telling J2EE container that this is stateless bean with mappedName=”HelloWorld” this is for Global JNDI For more information

CODE MyBean.java
package com.noppanit.ejb.bean;
import javax.ejb.Stateless;
import com.noppanit.ejb.interfaces.MyBeanFacade;
@Stateless(mappedName=”HelloWorld”)
public class MyBean implements MyBeanFacade
{
???????????????????? @Override
???????????????????? public String sayHello(String name) {
?????????????????????????????????????????? return “Hi “+name;
??????????????????????}
}

That’s it what you should do so for. The next thing is pack the project to .jar file and deploy it to your favorite J2EE container. For this topic I chose Glassfish, because it comes with J2EE package that I installed. You can see that we don’t have to create ejb-jar.xml at all, because this job is done by the power of annotation.

InitialContext context = new InitialContext(); <– // by default this line will look up in jndi.properties, but I’m using Global JNDI. So, we don’t have to create jndi.properties

And this is the code for Stand-alone client

CODE Client
public static void main(String[] args) throws Exception {
??????InitialContext context = new InitialContext();
??????MyBeanFacade bean = (MyBeanFacade)context.lookup(“HelloWorld”);
??????System.out.println(bean.sayHello(“Toy”));
}