Welcome to my blog

I blog my interests and opinions here.

Tuesday, December 14, 2010

EJB3: More programming less configuration

Using EJB3 makes programming a lot more fun that the previous versions. The advent of Java 5 annotations have made the life of programmers a lot more easier. Here is a simple Hello World stateles session bean EJB.

1. HelloWorldSessionBeanLocal - This is the EJB local interface that contains several methods that need to be implemented by the Session bean.

package hello;

import javax.ejb.Local;

import dto.Hello;

@Local
//@Local annotation indicates that the class is a EJB Local class
public interface HelloWorldSessionBeanLocal {

public String sayHello();

public String sayHelloFromDB();

public String sayHelloFromHibernate();

public void insertHelloUsingHibernate(Hello hello);

public Hello updateHelloUsingHibernate(Hello hello);

public void deleteHelloUsingHibernate(Hello hello);

}


2. HelloWorldSessionBean - The session bean has several methods.
a) sayHello method simply writes the string "Hello from Session bean" out.
b) sayHelloFromDB method writres the string out by reading from the database using Java Persistence API (JPA).
c) sayHelloFromHibernate method writes the string out by reading from the database using the Hibernate Dto Hello.class
d) insertHelloUsingHibernate(Hello hello) inserts a new record into the table using Hibernate
e) updateHelloUsingHibernate(Hello hello) updates the record in the database using Hibernate
f) deleteHelloUsingHibernate(Hello hello) deletes a record from the database using Hibernate


package hello;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import dto.Hello;
import dto.HelloHome;

/**
* Session Bean implementation class HelloWorldSessionBean
*/
@Stateless
// @Stateless indicates that this is a stateless session bean
public class HelloWorldSessionBean implements HelloWorldSessionBeanLocal {

@PersistenceContext(unitName="HelloWorldDS")
//@PersistenceContext indicates the JPA persistence context defined in the persistence.xml
EntityManager entityManager;

@EJB
// @EJB indicates that this HelloHome is an EJB. A reference is dynamically injected by the container rather than having to do JNDI lookups
HelloHome helloHome;

/**
* Default constructor.
*/
public HelloWorldSessionBean() {
// TODO Auto-generated constructor stub
}

public String sayHello()
{
return "Hello from Session Bean!";
}

public String sayHelloFromDB()
{
String ret = "";

try
{
javax.persistence.Query query = entityManager.createQuery("select Description from hello where id=1");
//org.hiberante.ejb.QueryImpl hs = (QueryImpl)query;
///org.hibernate.Query hbQuery = hs.getHibernateQuery();
ret = (String)query.getSingleResult();

}
catch(Exception ex)
{
System.out.println("Error when reading from DB"+ex.getMessage()+"\n"+ex.getStackTrace());
}


return ret;
}

public String sayHelloFromHibernate()
{
String ret = "";

try
{
Hello hello = helloHome.findById(1);
ret = hello.getDescription();

}
catch(Exception ex)
{
System.out.println("Error when reading from DB(Hibernate) "+ex.getMessage()+"\n"+ex.getStackTrace());
}


return ret;
}

public void insertHelloUsingHibernate(Hello hello)
{
try
{
helloHome.persist(hello);

}
catch(Exception ex)
{
System.out.println("Error when inserting DB(Hibernate) "+ex.getMessage()+"\n"+ex.getStackTrace());
}


}

public Hello updateHelloUsingHibernate(Hello hello)
{
Hello ret = null;

try
{
ret = helloHome.merge(hello);

}
catch(Exception ex)
{
System.out.println("Error when updating DB(Hibernate) "+ex.getMessage()+"\n"+ex.getStackTrace());
}


return ret;
}

public void deleteHelloUsingHibernate(Hello hello)
{
try
{
helloHome.remove(hello);

}
catch(Exception ex)
{
System.out.println("Error when deleting DB(Hibernate) "+ex.getMessage()+"\n"+ex.getStackTrace());
}


}

}

3. Hello - This is the auto generated Hibernate Dto class that maps to the hello table in the database

package dto;

// Generated Sep 13, 2010 2:17:01 PM by Hibernate Tools 3.3.0.GA

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
* Hello generated by hbm2java
*/
@Entity
// @Entity indicates that this is an database entity class
@Table(name = "hello", schema = "public")
// @Table indicates that this Dto maps to the database table "hello" in the "public" schema
public class Hello implements java.io.Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String description;

public Hello() {
}

public Hello(int id, String description) {
this.id = id;
this.description = description;
}

@Id
@Column(name = "id", unique = true, nullable = false)
//@Column indicates that this is a database column name
public int getId() {
return this.id;
}

public void setId(int id) {
this.id = id;
}

@Column(name = "description", nullable = false)
public String getDescription() {
return this.description;
}

public void setDescription(String description) {
this.description = description;
}

}

4. HelloHome - This is a stateless EJB that acts as the persistence manager for Hibernate to perform the datbase operation

package dto;

// Generated Sep 13, 2010 2:17:01 PM by Hibernate Tools 3.3.0.GA

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* Home object for domain model class Hello.
* @see dto.Hello
* @author Hibernate Tools
*/
@Stateless
// @Stateless indicates that this is a Stateless session bean
public class HelloHome {

private static final Log log = LogFactory.getLog(HelloHome.class);

@PersistenceContext(unitName="HelloWorldDS")
private EntityManager entityManager;

public void persist(Hello transientInstance) {
log.debug("persisting Hello instance");
try {
entityManager.persist(transientInstance);
log.debug("persist successful");
} catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}

public void remove(Hello persistentInstance) {
log.debug("removing Hello instance");
try {
entityManager.remove(persistentInstance);
log.debug("remove successful");
} catch (RuntimeException re) {
log.error("remove failed", re);
throw re;
}
}

public Hello merge(Hello detachedInstance) {
log.debug("merging Hello instance");
try {
Hello result = entityManager.merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}

public Hello findById(int id) {
log.debug("getting Hello instance with id: " + id);
try {
Hello instance = entityManager.find(Hello.class, id);
log.debug("get successful");
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
}

5. META-INF/persistence.xml - This file defines the persistence unit that the Hibernate entity manager should use. It in turn depends on the data source deployed on the application server such as JBoss / Websphere / Weblogic etc.

<?XML:NAMESPACE PREFIX = [default] http://java.sun.com/xml/ns/persistence NS = "http://java.sun.com/xml/ns/persistence" /><persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<!-- The name if this persistence unit is used by the JPA provider class -->
<persistence-unit name="HelloWorldDS">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:PostgresDS</jta-data-source>
</persistence-unit>
</persistence>

If you notice there are not many config files defined here. The Java 5 annotations in the class definitions took care of the attributes associated with the classes. Thus making life easier for the programmer.

No comments:

Post a Comment