J3 Limited
Testing The Installation Part Two


In the first part, Eclipse, and JBoss were tested by building a web application and a stateless EJB. In this section an entity EJB is created to test the database connectivity. Once this section has been completed, the infrastructure is known to be complete and functioning.

The source code for parts one and two of the installation tests can be downloaded as a zip archive from here.

Create Database Tables

A terminal window is opened, and mySQL command tool started on the same host as the mysql server.

Note: It is possible to access the server remotely. On Linux systems remote access for the mysql root user may not be enabled by default, as it poses a security risk.

Below is a sample session using the mysql command line tool. It is used to create a database called "shoestring". A new user called "user" with a password value of "password" is assigned to the shoestring database, with all privileges. Later on the new user can connect to mysql locally, or remotely, to create tables and add or delete data, in the shoestring database.

prompt> mysql -u root -p

Enter password: ********
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5 to server version: 5.0.18-standard

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> create database shoestring;
Query OK, 1 row affected (0.00 sec)

mysql> grant all privileges on shoestring.* to user identified by 'password';
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.02 sec)

mysql> select user, password, host from mysql.user where user='user';
| user | password                                  | host |
| user | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 | %    |
1 row in set (0.02 sec)

mysql> quit

Now that the new database and user is created. All operations on the database can be carried out using the username 'user'. This includes launching the mysql command line tool. The command tool can be launched with the -h hostname command line parameter if the server is not running on the same machine as the command line tool.

A script file is created called "createTestTable.sql". The contents are shown below, note that it deletes any existing database called shoestring:

CREATE DATABASE `shoestring`; 
USE `shoestring`;

CREATE TABLE `Address` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `line1` varchar(255) default NULL,
  `line2` varchar(255) default NULL,
  `line3` varchar(255) default NULL,
  `line4` varchar(255) default NULL,
  `country` varchar(150) default NULL,
  `postcode` varchar(50) default NULL,
  PRIMARY KEY  (`id`)

  `firstName` varchar(255) default NULL,
  `lastName` varchar(255) default NULL,
  `addressId` int(10) unsigned default NULL,
  `title` varchar(45) default NULL,
  `gender` varchar(20) default NULL,
  `dateOfBirth` datetime default NULL,
  `suffix` varchar(45) default NULL,
  `daytimePhone` varchar(45) default NULL,
  `eveningPhone` varchar(45) default NULL,
  `webSite` varchar(255) default NULL,
  `maritalStatus` varchar(20) default NULL,
  `id` int(10) unsigned NOT NULL auto_increment,
  `password` varchar(64) NOT NULL,
  `email` varchar(255) NOT NULL,
  `localeLanguage` varchar(2) default NULL,
  `localeCountry` varchar(2) default NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `FK_person_2` (`email`),
  KEY `FK_person_1` (`addressId`)

  ADD FOREIGN KEY (`addressId`) REFERENCES `Address` (`id`);

The command line tool is launched to run the script file in mysql, note that the user 'user' creates the table, not the mysql user root:

prompt> mysql -u user -p < createTestTable.sql
Enter password: ********


At this point, t he database, user and table are all created and working. We can check this from mysql. By logging on as the user 'user', the mysql system database is not visible. The shoestring database, to which the user has access, is visible:

prompt> mysql -u user -p
Enter password: ******** Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 16 to server version: 5.0.18-standard Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | shoestring | | test | +--------------------+ 2 rows in set (0.00 sec) mysql> use shoestring; Database changed mysql> show tables; +----------------------+ | Tables_in_shoestring | +----------------------+ | Address | | Person | +----------------------+ 1 row in set (0.00 sec) mysql>

A test record is added to the Person table:

mysql> insert into Person (firstName, lastName, email) 
  values ('Fred', 'Marzo','marzo@mail.com');
Query OK, 1 row affected (0.00 sec)

mysql> select firstName, lastName, email from Person;
| firstName | lastName | email          |
| Fred      | Marzo    | marzo@mail.com |
1 row in set (0.00 sec)

mysql> quit

At this point, the database is ready, with test data. The next step is to write some code to access the database.

Create An Entity EJB

In the Eclipse IDE's package explorer, com.j3ltd.test.ejbs is right clicked to create a new class:

The class is called Person, that is the same as the table in the database. It implements java.io.Serializable, so that the data can be passed to a web application.

The Person.java entity looks like this:

package com.j3ltd.test.ejbs;

import javax.persistence.*;

public class Person implements java.io.Serializable {
  private int id;
	private String email;
	private String firstName;
	private String lastName;
	public String getEmail() {
		return email;
	public void setEmail(String email) {
		this.email = email;
	public String getFirstName() {
		return firstName;
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	public String getLastName() {
		return lastName;
	public void setLastName(String lastName) {
		this.lastName = lastName;
	public int getId() {
return id;
public void setId(int id) {
this.id = id;
} }

The class is annotated with @Entity to denote that it is an entity bean. The get method for the id field is annotated with @Id to denote that id is the primary key in the table, id is also annotated with @GeneratedValue to denote that the key value is generated by the database.

That completes the entity EJB.

Use The Entity EJB

The entity EJB is used to get all the Person records in the table. The Stateless EJB developed in part one of this article is used to get a list of Person records.

The interface TestStateless.java is updated with a new method signature:

package com.j3ltd.test.ejbs;

import javax.ejb.Remote;
import java.util.*;

public interface TestStateless {
	public String testBean();
	public List<Person> getAllPersons();

The implementation class TestStatelessBean is updated to use the entity EJB Person to get all the records in the database and to return the list:

package com.j3ltd.test.ejbs;

import java.util.*;

import javax.ejb.Stateless;
import javax.persistence.*;

public @Stateless class TestStatelessBean implements TestStateless {
	@PersistenceContext(unitName="shoestringPU") private EntityManager em;
	public String testBean() {
		return "the server returned this string";

	public List<Person> getAllPersons() {
		ArrayList<Person> toReturn = new ArrayList();
		Query q = em.createQuery("SELECT o FROM Person o");
		for (Object po : q.getResultList()) {
			toReturn.add((Person) po);
		return toReturn;

Persistence.xml And The EntityManager

The EntityManager in the TestStatelessBean.java source (see previous section), uses the name "shoestringPU" to identify the persistence unit to use. This persistence unit is defined in a new file called persistence.xml, which is in the src folder of this project. The file's contents are as follows:

<?xml version="1.0" encoding="UTF-8"?>
  <persistence-unit name="shoestringPU">
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>

The persistence.xml file makes a link between the persistence unit and the datasource. The datasource was created and installed in JBoss during the installation section of this article (see here). The property hibernate.hbm2ddl.auto is not specified in the <properties> section. Valid values for hibernate.hbm2ddl.auto are create, create-drop and update. In this article, the database tables are not maintained by hibernate, they are created manually.

The file persistence.xml must be packaged along with the EJB class files. This is done by accessing the project properties, and selecting the packaging section:

The TestInstallation.ejb3 package is selected and right clicked to add the persistence.xml project file (which is in the src folder):

The Prefix entered is META-INF. This is the location within the archive where persistence.xml should be placed.

Update The Servlet

The servlet is updated to get the list of Person records and display them in the browser:

package com.j3ltd.test.web;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import java.io.*;
import java.util.*;
import com.j3ltd.test.ejbs.*;
public class TestStatelessEJBServlet extends HttpServlet { private TestStateless statelessBean; public void init() throws ServletException { try { Context context = new InitialContext(); statelessBean = (TestStateless) context.lookup("TestStatelessBean/remote"); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); writer.write("The stateless bean returned this string: " + statelessBean.testBean() + "\n"); List<person> people = statelessBean.getAllPersons(); for (Person person : people) { writer.write("Email retrieved: " + person.getEmail() + "\n"); } } }

That completes the coding. The files are all saved. And the packages built:

JBoss is launched from Eclipse, in debug mode:

Once JBoss has started up, the packages are deployed:

A browser is started and the url http://localhost:8080/TestInstallation/testStatetelessEJB is entered.

The browser displays the two test results performed by the servlet. The second line clearly shows the database record.

This completes the installation tests. At this stage Linux, Eclipse, JBoss, and MySQL are all working in harmony. The next step is to develop a realistic project that makes use of all the components installed and tested so far.

  Copyright © 2006 J3 Ltd Permission is granted to reproduce material on this page, on the condition that a reference to "WWW.J3Ltd.com" is given as the source of the material.