Title: Chapter 9b: Persistence Tier: Entity Beans
1Chapter 9bPersistence TierEntity Beans
Reference Eclipse WTP
2Objectives
- Entity Beans
- BMP and CMP
- Preparing JBoss and XDoclet
- Working with CMPs in Eclipse WTP
- EJB Query Language
3Persistence Layer Designs
Client and Presentation Tier
Business Tier
Service Layer (Facades)
Domain Model (POJO)
Data Layer (Data Access Object Interfaces)
Persistence Tier
1. JDBC (JDBC API)
2. EJB, CMP (Remote Stubs)
3. O/R Mapping (ORM Framework)
4Entity EJBs
- Entity beans represent persistent data
- Use entity beans as the interface between Java
components and relational or object-oriented
databases - The container uses the primary key to locate the
data when a client requests an entity bean and
creates only one bean to represent that data in a
Java object
5EJB to Database Schema Mapping
- Three approaches to database schema mapping
- Bottom-up mapping
- occurs when you have a database and can design
your EJBs to match the tables and columns defined
in the database schema - See textbook tutorial
- Top-down mapping
- possible when a new database is required and Java
developers are allowed to create databases - Meet-in-the-middle mapping
- Map to existing database and add new
attributes/columns
6Entity Beans BMP and CMP
- The EJB specification allows two approaches
- Container Managed Persistence (CMP)
- involves declaring the mapping between the
deployment descriptor and delegating all code
generation to the container - See textbook tutorial
- Bean Managed Persistence (BMP)
- Do-it-yourself (DIY) solution
- DIY alternative EJB Session Beans JDBC
- Note not covered in this course
7Preparing JBoss and XDoclet
- Reference Pages 393 397
- XDoclet set version to 1.2.3
- ejbdoclet set JBoss version to 4.0
8Working with CMPs
- Reference Pages 396 - 401
- General Steps using Eclipse WTP
- 1. Add a CMP EJB
- Map table to CMP Entity Bean
- 2. Modify CMP Entity Bean (e.g., LeagueBean)
- XDoclet generates
- Home and remote interfaces
- Data Source reference
- 3. Write the EJB Client (e.g., servlet)
- 4. Test the EJB Client
91. Add a LeagueBean CMP
- Right-click LeaguePlanetEJB project
- Invoke New XDoclet Enterprise JavaBean
- Java Package com.leagueplanet.cmp
- Class Name LeagueBean
- Select id as primary key.
10Sample CMP Entity Bean (1)
- package com.leagueplanet.cmp
-
- public abstract class LeagueBean implements
javax.ejb.EntityBean - public LeagueBean()
- public java.lang.Integer ejbCreate(int id,
String name) throws javax.ejb.CreateException - setId(id)
- setName(name)
- // EJB 2.0 spec says return null for CMP
ejbCreate methods. - return null
-
-
- public void ejbPostCreate() throws
javax.ejb.CreateException - public abstract java.lang.Integer getId()
- public abstract void setId(java.lang.Integer
id) - public abstract java.lang.String getName()
- public abstract void setName(java.lang.String
name)
11Sample CMP Entity Bean (2)
- public void ejbActivate() throws EJBException,
RemoteException - public void ejbLoad() throws EJBException,
RemoteException - public void ejbPassivate() throws EJBException,
RemoteException - public void ejbRemove() throws RemoveException,
EJBException, - RemoteException
- public void ejbStore() throws EJBException,
RemoteException - public void setEntityContext(EntityContext arg0)
throws EJBException, - RemoteException
- public void unsetEntityContext() throws
EJBException, RemoteException -
-
122. Modify CMP Entity Bean
- Reference Textbook page 403
- Using XDoclet in Eclipse WTP, update
_at_jboss.persistence XDoclet tag with - _at_jboss.persistence datasource"java/Leagu
eDS" datasource-mapping"Derby"
table-name"APP.GAME" create-table"true"
remove-table"false" alter-table"true"
13JBoss and Data Sources
- Entity beans locate data sources (e.g., Derby
JDBC driver) by looking up the name (e.g.,
LeagueDS) in a JNDI server (i.e., part of JBoss) - JBoss loads the data source configuration (e.g.,
derby-ds.xml) at start-up - You must restart JBoss when configuration file is
modified.
14Define Data Source
- Define data source in the JBoss-specific
configuration file (e.g., derby-ds.xml) - Location C\dev\appservers\jboss-4.2.2.GA\server\
default\deploy - ltlocal-tx-datasourcegt
- ltjndi-namegtLeagueDSlt/jndi-namegt
- ltconnection-urlgt jdbcderby//localhost1527
/leagueDBlt/connection-urlgt - ltdriver-classgtorg.apache.derby.jdbc.ClientDr
iverlt/driver-classgt - ltuser-namegttestlt/user-namegt
- ltpasswordgttestlt/passwordgt
- ltmin-pool-sizegt5lt/min-pool-sizegt
- ltmax-pool-sizegt20lt/max-pool-sizegt
- ltidle-timeout-minutesgt5lt/idle-timeout-minute
sgt - lt/local-tx-datasourcegt
15Add a Service Layer for CMP (1)
- E.g., IceHockeyCMPDAOImpl class
- Add createLeagueFromCMP() method as follows
- private League createLeagueFromCMP(
com.leagueplanet.cmp.League cmp)throws
SQLException, ParseException, RemoteException
   League league new League()  Â
league.setId(cmp.getId().intValue())Â Â Â
league.setName(cmp.getName())Â Â Â return
league
16Add a Service Layer for CMP (2)
- Update findLeague(long id) method as follows
- public League findLeague(long id) Â Â Â // League
leaguenew League(id, "Rosehill Girl's Hockey
League")   int leagueId (int) id   League
league null   try       Â
com.leagueplanet.cmp.League cmp
com.leagueplanet.cmp.LeagueUtil          Â
.getHome().findByPrimaryKey(new
Integer(leagueId))Â Â Â Â Â Â Â league
createLeagueFromCMP(cmp)Â Â Â Â Â Â Â
league.getSchedules().add(findSchedule(leagueId))
   catch (Exception e)       Â
e.printStackTrace()Â Â Â Â Â Â return league
173. Write EJB Client
- E.g., LeagueCRUDServlet class
- protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException - try
- // Test cases for LeagueCMP
- System.out.println("1. Create a new league
(direct approach using remote home)") - int id Integer.parseInt(request.getParameter("i
d")) - String name request.getParameter("name")
- // this will create a new row in Derby DB
- LeagueUtil.getHome().create(id, name)
- System.out.println("2. Find league (direct
approach using remote home)") - com.leagueplanet.cmp.League dbrow
LeagueUtil.getHome().findByPrimaryKey(id) - System.out.println("League id "
dbrow.getId() " name" dbrow.getName())
18Sample EJB Client (2)
- System.out.println("3. Update name of league
(direct approach using local home)") - // creates an instance of league facade, then
calls the find method - LeagueLocal localdbrow LeagueUtil.getLocalHome()
- .findByPrimaryKey(id)
- // this will update name column in Derby DB
- localdbrow.setName(name " - correction")
- System.out.println("4. Find league (direct
approach using local home)") - localdbrow LeagueUtil.getLocalHome().findByPrima
ryKey(id) - System.out.println("League id "
localdbrow.getId() " name"
localdbrow.getName())
19Sample EJB Client (3)
- System.out.println("5. Delete current league
record") - // this will delete the row in Derby DB
- localdbrow.remove()
- System.out.println("6. Find deleted league
(multi-tier approach using facade remote
home)") - // creates an instance of league facade, then
calls the find method - LeagueFacade facade LeagueFacadeUtil.getHome().
create() - // The findLeague() method in facade calls
findByPrimaryKey() using local home - // and returns a POJO (non-CMP) League object
- League league facade.findLeague(id)
- System.out.println("League id "
league.getId() " name" league.getName()) - catch (Exception e)
- System.err.println("exception occurred. "
e.getMessage()) -
204. Test EJB Client
- http//localhost8080/LeaguePlanetWeb/LeagueCRUDSe
rvlet?id6nameLeague6 - Console Output
- 174452,593 INFO STDOUT 1. Create a new league
(direct approach using remote home) - 174452,609 INFO STDOUT 2. Find league (direct
approach using remote home) - 174452,609 INFO STDOUT League id 6
nameLeague6 - 174452,609 INFO STDOUT 3. Update name of
league (direct approach using local home) - 174452,625 INFO STDOUT 4. Find league (direct
approach using local home) - 174452,625 INFO STDOUT League id 6
nameLeague6 - correction - 174452,625 INFO STDOUT 5. Delete current
league record - 174452,640 INFO STDOUT 6. Find deleted league
(multi-tier approach using facade remote home) - 174452,640 ERROR STDERR javax.ejb.ObjectNotFou
ndException No such entity!
21EJB Query Language
- Enterprise JavaBean Query Language (EJB QL) was
introduced in the EJB 2.0 specification to
support the abstract persistence model - EJB QL language for expressing the equivalent of
SQL SELECT statements for CMP beans - Useful for generating code for custom Find method
- E.g. findAll() method
- _at_ejb.finder query"SELECT OBJECT(a) FROM
LeagueSCHEMA as a" - signature"java.util.Collection findAll()
22Comparing EJB QL and SQL Statements
Note More details in Mastering EJB 3.0, Chapter 9
23Sample Finder Methods XDoclet Tags in
GameBean.java
- _at_ejb.finder
- query"SELECT OBJECT(a) FROM GameSCHEMA as a"
- signature"java.util.Collection findAll()"
-
- _at_ejb.finder
- query"SELECT OBJECT(a) FROM GameSCHEMA as a
WHERE a.scheduleid ?1" - signature"java.util.Collection
findScheduleGames(int scheduleid)" -
24Generated Deployment Descriptor (ejb-jar.xml)
ltquerygt ltquery-methodgt
ltmethod-namegtfindAlllt/method-namegt
ltmethod-paramsgt lt/method-paramsgt
lt/query-methodgt
ltejb-qlgtlt!CDATASELECT OBJECT(a) FROM GameSCHEMA
as a gtlt/ejb-qlgt lt/querygt
ltquerygt ltquery-methodgt
ltmethod-namegtfindScheduleGameslt/method-namegt
ltmethod-paramsgt
ltmethod-paramgtintlt/method-paramgt
lt/method-paramsgt lt/query-methodgt
ltejb-qlgtlt!CDATASELECT OBJECT(a) FROM
GameSCHEMA as a WHERE a.scheduleid
?1gtlt/ejb-qlgt lt/querygt
25Next Steps
- Tutorials
- Chapter 9 Iteration 3
- Lab
- EJB CMP (add, find, edit and delete League)
- Assignment 4