+ All Categories
Home > Documents > IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I....

IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I....

Date post: 15-Jul-2020
Category:
Upload: others
View: 10 times
Download: 0 times
Share this document with a friend
21
TON DUC THANG UNIVERSITY Faculty of Information Technology Phuc Duong [email protected] 1 IS502052: Enterprise Systems Development Concepts Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing, persisting, and managing data between Java objects / classes and a relational database. JPA was defined as part of the EJB 3.0 specification as a replacement for the EJB 2 CMP Entity Beans specification. JPA is now considered the standard industry approach for Object to Relational Mapping (ORM) in the Java Industry. JPA itself is just a specification, not a product; it cannot perform persistence or anything else by itself. JPA is just a set of interfaces, and requires an implementation. Following are the key actors in persistence API: - Entity A persistent object representing the data-store record. It is good to be serializable. - EntityManager Persistence interface to do data operations like add/delete/update/find on persistent object (entity). It also helps to execute queries using Query interface. - Persistence unit (persistence.xml) Persistence unit describes the properties of persistence mechanism. - Data Source (jboss.xml) Data Source describes the data-store related properties like connection URL, user-name, password, etc. To implement EJB persistence mechanism, we need to do the following tasks: - Step 1 Create table in database. - Step 2 Create Entity class corresponding to table. - Step 3 Create Data Source and Persistence Unit. - Step 4 Create a stateless EJB having EntityManager instance. - Step 5 Update stateless EJB, implement methods to add records and get records from database via entity manager. - Step 6 A console based application client will access the stateless EJB to persist data in database. In this lab tutorial, we will implement a stateless EJB to access remote database and insert data into it. This application illustrates a bookstore. II. Create database and data source To create table in database, we need the following software: - PostgreSQL and pgAdmin. - JBoss EAP management. 1. Create database and insert table, data We will create a book table in SampleDB1 database.
Transcript
Page 1: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 1

IS502052: Enterprise Systems Development Concepts

Lab 7: EJB Persistence Architecture

I. Introduction

The Java Persistence API (JPA) is a Java specification for accessing, persisting, and managing data

between Java objects / classes and a relational database. JPA was defined as part of the EJB 3.0 specification

as a replacement for the EJB 2 CMP Entity Beans specification. JPA is now considered the standard

industry approach for Object to Relational Mapping (ORM) in the Java Industry.

JPA itself is just a specification, not a product; it cannot perform persistence or anything else by itself. JPA

is just a set of interfaces, and requires an implementation.

Following are the key actors in persistence API:

- Entity – A persistent object representing the data-store record. It is good to be serializable.

- EntityManager – Persistence interface to do data operations like add/delete/update/find on

persistent object (entity). It also helps to execute queries using Query interface.

- Persistence unit (persistence.xml) – Persistence unit describes the properties of persistence

mechanism.

- Data Source (jboss.xml) – Data Source describes the data-store related properties like connection

URL, user-name, password, etc.

To implement EJB persistence mechanism, we need to do the following tasks:

- Step 1 – Create table in database.

- Step 2 – Create Entity class corresponding to table.

- Step 3 – Create Data Source and Persistence Unit.

- Step 4 – Create a stateless EJB having EntityManager instance.

- Step 5 – Update stateless EJB, implement methods to add records and get records from database

via entity manager.

- Step 6 – A console based application client will access the stateless EJB to persist data in database.

In this lab tutorial, we will implement a stateless EJB to access remote database and insert data into it. This

application illustrates a bookstore.

II. Create database and data source

To create table in database, we need the following software:

- PostgreSQL and pgAdmin.

- JBoss EAP management.

1. Create database and insert table, data

We will create a book table in SampleDB1 database.

Page 2: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 2

First, open pgAdmin and check whether PostgreSQL instance is available. If not, you need to install

PostgreSQL and open pgAdmin again.

Figure 1 Connect to PostgreSQL server

Right-click on PostgreSQL 9.6 instance and select Connect Server to establish connection (Figure 1).

Second, to create new database, right-click on Database and select Create > Database (Figure 2).

Figure 2 Create new database

Enter SampleDB1 as database's name, and keep everything in default value. Then, click Save (Figure 3).

Figure 3 Name the database

Page 3: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 3

After PostgreSQL processing, we will have a new database, as in Figure 4.

Figure 4 PostgreSQL structure

Third, to create table, expand Schemes > public > Tables option, as in Figure 5.

Figure 5 Expand to public schema

Now, right-click on Tables and select Create > Table. Then, enter book for table's name and switch to

Columns tab.

Page 4: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 4

Figure 6 Create table wizard

In Columns tab, click + symbol on right-side of the window to add new column. You need to add two new

columns as in Figure 7. Then, click Save.

Figure 7 Add new columns

If successfully, we will have the same structure as this:

Page 5: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 5

Figure 8 Schema structure after inserting new table

Since we want the book's ID is just integer number, we will set this property to auto-increment. You need

to expand Tables > book > Columns > id, then, right-click on id and select CREATE Script.

A new tab will be opened, and you can copy/paste the following code:

CREATE SEQUENCE book_id_seq;

ALTER TABLE public.book

ALTER COLUMN id SET DEFAULT nextval('book_id_seq'::regclass);

Then, click the lightning button (or, press F5 key) to execute the commands.

Finally, we should insert some records into this new table. Right-click on book instance, select Scripts >

INSERT script.

Figure 9 Create INSERT script

A new tab will be opened, and copy/paste the following code. You should notice that we eliminate id

column from INSERT query.

INSERT INTO public.book(name)

VALUES ('Concepts of Programming Languages (10th Edition)');

INSERT INTO public.book(name)

VALUES ('Fundamentals of Database Systems (7th Edition)');

After executing the INSERT query, let's check the result. Right-click on book instance in Browser

windows, select View/Edit Data > All Rows.

Page 6: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 6

If everything is fine until this step, you can get the following screen.

Figure 10 Data in book table

2. Deploy PostgreSQL in JBoss

If you are familiar with Java and working with database in Java environment, you know that there is JDBC

API, which supports manipulating database in Java. However, in this lab tutorial, we want to put the

SampleDB1 database behind the JBoss server, thus, we treat it as a data source in JBoss server.

Firstly, we need to deploy PostgreSQL API to JBoss server, as a datasource driver. Open NetBeans, start

the WildFly Application Server, and open Admin Console. Then, do the following steps:

- Navigate to Deployments tab and click Add button;

- In New Deployment window, choose Upload a new deployment and click Next;

Figure 11 Upload new deployment wizard

Page 7: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 7

- To upload deployment archive, click Choose File and point to postgresql-42.1.4.jar1 file. Then,

click Next;

- In final step, we name this deployment as postgresql-42.1.4.jar in both Name and Runtime Name

fields, and click Finish.

Figure 12 Final step in deployment task

3. Connect database to SampleDB1-DS

Now, we are having PostgreSQL API in JBoss, we just connect the SampleDB1 database to JBoss and use

postgresql-42.1.4.jar driver, that's it.

You should do these steps below:

- Open JBoss EAP Management (aka Admin Console);

- Click Start in Create a Datasource section in Configuration block;

Figure 13 Add new data source

1 http://it.tdt.edu.vn/~dhphuc/teaching/is502052/files/postgresql-42.1.4.jar

Page 8: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 8

- Expand Subsystems > Datasources > Non-XA2, and click Add in Datasource section;

- It will open Create Datasource wizard, you need to select PostgreSQL Datasource. Then, click

Next;

Figure 14 Create Datasource wizard

- In step 1/3, you name SampleDB1-DS for datasource's name and java:/SampleDB1-DS for JNDI

name. Then, click Next;

Figure 15 Create datasource (1/3)

- In step 2/3, setup JDBC driver, switch to Detected Driver tab and choose postgresql-42.1.4.jar;

2 A non-XA transaction always involves just one resource. Conversely, XA may span multiple resources.

Page 9: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 9

Figure 16 Create datasource (2/3)

- In step 3/3, you need to configure the URL, username, password. For the URL, it can be

"jdbc:postgresql://localhost:5432/SampleDB1". The username and password to connect to

PostgreSQL depend on your system.

Figure 17 Create datasource (3/3)

- Confirm the information and click Finish (Figure 18).

Page 10: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 10

Figure 18 Confirm connection information

Before going on, you should to test the connection can establish from SampleDB1-DS (data source on

JBoss server) to SampleDB1 (database on PostgreSQL) via postgresql-42.1.4.jar driver.

Figure 19 Test connection

III. Create Entity class

After completing Section 2, we have already had data source of SampleDB1 database. In this section, we

will create EJB application to access data source on JBoss server.

1. Register JDBC driver of SampleDB1 database

In NetBeans, switch to Services tab in Project Explorer panel:

Page 11: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 11

- Right-click on Databases and select New Connection;

- In new connection wizard, choose PostgreSQL in Driver drop-box;

Figure 20 New connection wizard

- In the next step (as in Figure 21), you need to specify: host, port, database's name,

username/password, JDBC URL. All this information depends on your system. Click Next, since

you must select the database's schema.

Figure 21 Configure database connection

- In schema selection step, select public schema, since our tables are in it.

Page 12: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 12

Figure 22 Select schema

- In final step, you can configure the input connection name, or leave it as default.

Figure 23 Specify input connection name

- Check the connection status by looking the database connection icon. A broken icon represents that

the database is not connected.

Page 13: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 13

2. Create Entity class

You need to do the following steps to create Entity class:

- Create edu.tdt.persistence package;

- Right-click on created package, then, select New > Other;

- Choose Persistence in Categories and Entity Classes from Database in File Types (Figure 24);

Figure 24 Create new file

- In next step, select data source and tables.

Figure 25 Select datasource and tables

- Configure Entity Class in step 3/4, as in Figure 26.

Page 14: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 14

Figure 26 Configure Entity Class

- In final step, configure mapping options as in F.

Figure 27 Configure mapping options

- After NetBeans creates new entity class successfully, the project's structure is as follows.

Page 15: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 15

Figure 28 Project structure

Since we create Book entity by using NetBeans wizard, we can leave it as default. Besides that, NetBeans

will also create two important configuration files: jboss.xml and persistence.xml.

Now, we must edit these two configuration files. We can leave persistence.xml as default, if we don't

configure any information. However, jboss.xml is empty, you need to copy/paste the following code to it:

<?xml version="1.0" encoding="UTF-8"?>

<?xml version="1.0" encoding="UTF-8"?>

<datasources>

<local-tx-datasource>

<jndi-name>PostgresDS</jndi-name>

<connection-url>jdbc:postgresql://localhost:5432/SampleDB1</connection-url>

<driver-class>org.postgresql.driver</driver-class>

<user-name>admin</user-name>

<password>12345678</password>

<min-pool-size>5</min-pool-size>

<max-pool-size>20</max-pool-size>

<idle-timeout-minutes>5</idle-timeout-minutes>

</local-tx-datasource>

</datasources>

IV. Create Stateless EJB Application

1. Create Stateless EJB

In this section, everything is back to normal. You can reference the previous lab tutorials to implement a

stateless EJB application. However, in this lab sample, there is something different.

Do the following steps:

- Right-click on edu.tdt.persistence, and create new stateless session bean, named

LibraryPersistentBean.

Page 16: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 16

Figure 29 Create new stateless EJB

- Then, rename the LibraryPersistentBeanLocal.java to LibraryPersistentBeanRemote.java, as in

previous lab tutorials. Then, add the following two methods:

package edu.tdt.persistence;

import java.util.List;

import javax.ejb.Remote;

@Remote

public interface LibraryPersistentBeanRemote {

void addBook(Book bookName);

List<Book> getBooks();

}

- Open LibraryPersistentBean.java to implement the two interface's methods. To get persistence's

unit name, refer to persistence.xml configuration file.

package edu.tdt.persistence;

import java.util.List;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

@Stateless

public class LibraryPersistentBean implements LibraryPersistentBeanRemote {

@PersistenceContext(unitName = "SampleEJB3PU")

private EntityManager entityManager;

public LibraryPersistentBean() {

}

@Override

public void addBook(Book book) {

entityManager.persist(book);

}

@Override

public List<Book> getBooks() {

return entityManager.createNamedQuery("Book.findAll").getResultList();

}

}

Page 17: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 17

- Then, build and deploy this project to JBoss server.

2. Create EJB Tester

After implement two interface's methods, we need to create an EJB Tester, as in previous lab tutorials. Do

the following steps:

- Create new Java project, named SampleEJB3Test.

- Create jndi.properties and jboss-ejb-client.properties (place in src directory).

- Add SampleEJB3 project and jboss-client.jar to project's classpath.

- Create EJBTester.java in edu.tdt.test, as follows:

package edu.tdt.test;

import edu.tdt.persistence.Book;

import edu.tdt.persistence.LibraryPersistentBean;

import edu.tdt.persistence.LibraryPersistentBeanRemote;

import java.io.FileInputStream;

import java.io.IOException;

import java.util.List;

import java.util.Properties;

import java.util.Scanner;

import javax.naming.InitialContext;

import javax.naming.NamingException;

public class EJBTester {

private Properties props;

private InitialContext ctx;

public EJBTester()

{

readJNDI();

}

/**

* Read the JNDI properties file

*/

private void readJNDI()

{

props = new Properties();

try

{

props.load(new FileInputStream("jndi.properties"));

} catch(IOException e)

{

System.err.println(e.toString());

}

try

{

ctx = new InitialContext(props);

//ctx.close();

} catch (NamingException ex)

{

ex.getMessage();

}

}

/**

* Construct and return the JNDI address of called class

* @return String

*/

private String getJNDI()

{

String appName = "";

String moduleName = "SampleEJB3";

String distinctName = "";

String sessionBeanName = LibraryPersistentBean.class.getSimpleName();

String viewClassName = LibraryPersistentBeanRemote.class.getName();

Page 18: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 18

return "ejb:"+appName+"/"+moduleName+"/"+distinctName+"/"+sessionBeanName+"!"+viewClassName;

}

/**

* Show the GUI in console window

*/

private void showGUI()

{

System.out.println("\n=========================");

System.out.println("Welcome to TDTU Bookstore");

System.out.println("=========================");

System.out.print("Options: \n1. Add Book \n2. List All Books (Current Session) \n3. List All

Books (New Session) \n4. Exit \nEnter Choice: ");

}

/**

* Declare a bean to invoke getBooks() method in LibrarySessionBeanRemote

*/

private void getAllBooks()

{

try

{

// We can define another bean to access the LibrarySessionBeanRemote

LibraryPersistentBeanRemote libBean2 = (LibraryPersistentBeanRemote) ctx.lookup(getJNDI());

List<Book> booksList = libBean2.getBooks();

// Print all books

if(booksList.isEmpty())

{

System.out.println("There is no book in the bookstore!\n");

return;

}

System.out.println("\n=========================");

System.out.println("Listing Books in TDTU Bookstore");

System.out.println("=========================");

for (int i = 0; i < booksList.size(); i++)

{

System.out.println((i+1) + "\t" + booksList.get(i));

}

System.out.println();

} catch (NamingException ex)

{

ex.getMessage();

}

}

/**

* Test the Stateless EJB

*/

public void testEntityEJB()

{

try

{

// Scanner definition

Scanner sc = new Scanner(System.in);

// Lookup the LibrarySessionBeanRemote

LibraryPersistentBeanRemote libBean = (LibraryPersistentBeanRemote) ctx.lookup(getJNDI());

int choice = 0;

while(choice != 4)

{

this.showGUI();

// Use this approach to avoid the error cause by nextInt() follows by nextLine()

choice = Integer.parseInt(sc.nextLine());

if(choice == 1)

{

// Add a book

System.out.print("Enter book name: ");

String bookName = sc.nextLine();

Book b = new Book();

b.setName(bookName);

Page 19: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 19

libBean.addBook(b);

}

else if(choice == 2)

{

// Print all books (using current session bean)

List<Book> booksList = libBean.getBooks();

if(booksList.isEmpty())

{

System.out.println("There is no book in the bookstore!\n");

}

System.out.println("\n=========================");

System.out.println("Listing Books in TDTU Bookstore");

System.out.println("=========================");

for (int i = 0; i < booksList.size(); i++)

{

System.out.println((i+1) + "\t" + booksList.get(i));

}

System.out.println();

}

else if(choice == 3)

{

// Print all books (using new session bean)

getAllBooks();

}

else

{

// Exit

break;

}

}

sc.close();

} catch (NamingException ex)

{

ex.getMessage();

}

}

}

- Create main method to test EJBTester class.

package edu.tdt.test;

public class Test {

public static void main(String[] args)

{

EJBTester ejb = new EJBTester();

ejb.testEntityEJB();

}

}

- You should notice that we don't specify id attribute when adding new book to datasource.

3. Run the project

Click run the project (or press F6 key). Test the project by following flow:

- Enter 2 and check the output (Figure 30).

Page 20: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 20

Figure 30 Output (1)

- If you want to change the output is book's name, edit toString() method in Book class (Figure 31).

Figure 31 Output (2)

- Run project (if necessary), enter 1 to insert new book to datasource. Then, enter 2 to list all books.

Figure 32 Output (3)

- Stop the current running by entering 4. Now, run project again and enter 3 to list all books by using

another session bean.

Page 21: IS502052: Enterprise Systems Development Concepts Lab 7 ...Lab 7: EJB Persistence Architecture I. Introduction The Java Persistence API (JPA) is a Java specification for accessing,

TON DUC THANG UNIVERSITY

Faculty of Information Technology

Phuc Duong – [email protected] 21

Figure 33 Output (3)

- Open pgAdmin and navigate to SampleDB1/Schemas/Tables/book. Then, right-click on book

instance and select View/Edit Data > All Rows. Figure 34 shows above states that books are

getting stored in persistent storage and/or retrieved from database.

Figure 34 Retrieve data in PostgreSQL

V. Exercises

1. Create a new stateful EJB to connect to datasource on JBoss server, as in the above sample application.


Recommended