How to create EJB 3.1

This post describes how to create an simple Entity and Session bean with EJB3.1. As some of you know EJB 3.1 is ready to use and makes the world much easier for the developers. No more xml configuration files except “persistence.xml”. Everything can be done using annotations and if you decide to use xml configuration files they overrule the annotations.

I am telling you using EJB now is as easy as programming POJOs. This is how you define an simple Entity bean.


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;

@NamedQuery(name=Item.findAll,query="SELECT item from Item item")
public class Item
	public final static String findAll = "";

    	@GeneratedValue(strategy = GenerationType.AUTO)
    	private Long itemid;

	private String itemName;

	public String getItemName()
		return itemName;

	public void setItemName(String itemName)
		this.itemName = itemName;

	public Long getItemid()
		return itemid;

And this is how you define an simple Session bean.


import java.util.List;

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

public class ItemService
	@PersistenceContext(unitName = "itemDataBase")
	EntityManager em;

	public void save(Item item)

	public Item findItem(long id)
		return this.em.find(Item.class, id);

	public List<Item> getItems()
		return this.em.createNamedQuery(Item.findAll).getResultList();

	public void delete(long itemid)
		Item item = findItem(itemid);
		if (item != null)

To be able to save the entity you need some kind of an persistence, this is an example of the persistance.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="" xmlns:xsi="" xsi:schemaLocation="">
  <persistence-unit name="itemDataBase" transaction-type="JTA">
      <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>

This is it, this is all you need to create an ejb jar file that is deployable to the server.