A simple JEE 5 Application
In this tutorial, you will learn how to create a simple application with JEE5 and to deploy it on Glassfish. Check this article if you need more information about development using eclipse glassfish and mysql.
- Create the Player Table in MySql
- Create a JPA Project with an entity
- Create a CRUD Facade
- Create a Servlet
- Package the application in an ear an deploy it on Glassfish
The whole source code is available from the kenai’s repository:http://kenai.com/projects/javaee-tutorial
Create the Player Table in MySql
Make sure you have MySql started and create a new database called tennis. In Eclipse, open the Database Development perspective. Right click on Database Connections in the Data Source Explorer.

Choose MySql, click on next and fill the connection profile information

Verify that eclipse can connect to your database by clicking on Test Connection.
Open the following script in the Sql Editor of Eclipse and set the connection profile:
ALTER TABLE PLAYER DROP PRIMARY KEY; DROP TABLE PLAYER; CREATE TABLE PLAYER ( id INT NOT NULL, firstname VARCHAR(50) NOT NULL, lastname VARCHAR(50) NOT NULL, birthdate DATE NOT NULL, PRIMARY KEY (id) ) ENGINE=MyISAM;
Right click in the script and choose Execute All.
Verify that the operation is successful and check the the table PLAYER appears in the connection explorer.

Create a JPA Project with an entity
Now that we have created the table PLAYER, we gonna create an entity Bean that map to this table.
Switch back to the JEE Perspective and create a new JPA Project.

Configure the persistence framework for JPA, we can choose between TopLink, Hibernate, EclipseLink, … For this tutorial, we will use EclipseLink

Right click on your JPA Project and create a new entities from table. Select MySql Connection, the schema tennis and the table PLAYER.

No table association is needed, but check the customize entity window and click on finish.

Check the generated Player class :
package ch.creasystem.tennis.playermgmt.entities;
/**
* Entity implementation class for Entity: Player
*
*/
@Entity
@Table(name = "player", schema = "tennis")
public class Player implements Serializable {
/**
* UID
*/
private static final long serialVersionUID = -5797389455799204546L;
@Id
private long id;
private String firstname;
private String lastname;
@Temporal(TemporalType.DATE)
private Date birthdate;
// getter, setter and toString()
....
The @Temporal(TemporalType.DATE) means that you just need the date (no time).
And the datasource mysql the persistence.xml:
mysql ch.creasystem.tennis.playermgmt.entities.Player
Your application server must have a datasource configured with name mysql. For more information how to configure a connection pool on Glassfish, see development using eclipse glassfish and mysql.
Create a CRUD Facade
Because only the Web container access this facade, we gonna create a stateless session bean with local interface. Each calls to the Facade will occurs in a new Transaction (TransactionAttributeType.REQUIRES_NEW). A CRUD Facade is in fact an exposed transactional DAO. To simplify, the facade will not use a dedicated DAO, but direct access the PersistenceContext.
Create a new EJB Project called TennisEJB, make sure you choose version 3.0 and add it to a TennisEar.

In the java build path, add a new project reference to the tennisJPA project.
Right click on the TennisEJB project and choose new -> Session Bean (EJB 3.x)

Open the PlayerMgmtService interface and declare these methods :
@Local
public interface PlayerMgmtService {
/**
* Create a new player
* @param name
* @param lastname
* @param birthdate
* @return the newly created player
*/
public Player createPlayer(String name, String lastname, Date birthdate);
/**
* Find a player with the specified playerId
* @param playerId
* @return the player or null if not found
*/
public Player getPlayerById(Long playerId);
/**
* Find all players
* @return the list of all players
*/
public List getAllPlayers();
/**
* update the specified player
* @param player
* @return the updated player
*/
public Player updatePlayer(Player player) ;
/**
* delete the specified player
* @param playerId
*/
public void deletePlayer(Long playerId);
}
Notice the @Local annotation to indicate the local interface.
Implements these methods in the PlayerSession bean :
/**
* Bean implementation class PlayerMgmtService
*/
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class PlayerMgmtServiceBean implements PlayerMgmtService {
@PersistenceContext
EntityManager em;
public Player createPlayer(String name, String lastname, Date birthdate) {
Player player = new Player();
player.setFirstname(name);
player.setLastname(lastname);
player.setBirthdate(new java.sql.Date(birthdate.getTime()));
this.em.persist(player);
return player;
}
@SuppressWarnings("unchecked")
public List getAllPlayers() {
Query query = em.createQuery("SELECT p FROM Player p");
List resultList = query.getResultList();
return resultList;
}
public Player getPlayerById(Long playerId) {
return em.find(Player.class, playerId);
}
public Player updatePlayer(Player player) {
return em.merge(player);
}
public void deletePlayer(Long playerId) {
Player player = em.find(Player.class, playerId);
if (player != null) {
em.remove(player);
}
}
}
Notice the @Stateless annotation to indicate that this class is a stateless session bean. The Entity Manager is simply injected with the @PersistenceContext annotation.
Create a Servlet
Create a new Dynamic Web Project and add it to the TennisEar.

Create a new Servlet called TennisServet

Add a project reference to the TennisEJB and TennisJPA project. Inject the service interface using @EJB annotation and implements the service() method:
/**
* EJB Injection of the PlayerMgmtService
*/
@EJB
PlayerMgmtService playerBean;
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
// create a new user
if ("create".equals(action)) {
try {
String firstname=request.getParameter("firstname");
String lastname=request.getParameter("lastname");
SimpleDateFormat dateFormat = new SimpleDateFormat("DD-MM-yyyy");
Date date = dateFormat.parse(request.getParameter("birthdate"));
playerBean.createPlayer(firstname, lastname, date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// delete an existing player
if ("delete".equals(action)) {
Long id = Long.parseLong(request.getParameter("id"));
playerBean.deletePlayer(id);
}
// list all player and set the list as request attribute
List players = playerBean.getAllPlayers();
request.setAttribute("playerlist", players);
RequestDispatcher dispatcher = request.getRequestDispatcher("tennis/playerlist.jsp");
dispatcher.forward(request, response);
}
Create the playerlist.jsp to provide the player management:
<table>
<tr>
<td>Id</td>
<td>Firstname</td>
<td>Lastname</td>
<td>Birthdate</td>
<td></td>
</tr>
<c:forEach var="player" items="${playerlist}">
<tr>
<td>${player.id}</td>
<td>${player.firstname}</td>
<td>${player.lastname}</td>
<td>${player.birthdate}</td>
<td><a href="TennisServlet?action=delete&id=${player.id}">delete</a></td>
</tr>
</c:forEach>
</table>
Package the app in an ear an deploy it on Glassfish
Make sure Glassfish is started and right click on it in the Servers view. choose Add/Remove ..

Publish the application. Check in the log that Glassfish has successfully published the TennisEar application.
Open this Url in a browser http://localhost:8080/Tennis4Web/TennisServlet to test the player management Application.

Well done ! you have created your first JEE 5 application with a servlet, session bean and an entity bean. As you can see, Eclipse has plenty of wizards generating templates for most of the JEE components making the development for the JEE5 platform much easier than before. thanks to the JEE5 specification, deployment descriptors are no longer needed (but you still can use them), and the EJB development is much easier than for the J2EE platform.
Suivre les commetaires avec le flux RSS 2.0. Vous pouvez laisser un comentaire, or trackback depuis votre site.
cnous.ch
e-annuaire.ch
webliste.ch
I want to quote your post in my blog. It can?
And you et an account on Twitter?
No problem