introduction to enterprise javabeans
TRANSCRIPT
Introduction To Enterprise JavaBeans
Introduction to Enterprise JavaBeans
Pasquale Imbemba, 9.4
AUTONOME PROVINZ BOZEN - SDTIROLPROVINCIA AUTONOMA DI BOLZANO - ALTO ADIGERipartizione 9 - InformaticaAbteilung 9 - InformationstechnikAmt 9.4 Amt fr technisch-wirtschaftliche Informatik
Ufficio 9.4 Informatica tecnica-economica
Contents
What they teach you at school
Naming and legacy
The need for distributed componentsConsequences
Enterprise JavaBeansSession Beans
Entity BeansRelationships
Entity ManagerPersistence Unit and Persistence Context
Interface
Contents
Message Driven BeansA use case
Advanced Entity BeansSecondary Table
Inheritance strategies
Timer Service
Bibliography
What they teach you at school
Code reuse improves code stabilityLess error proneBugs deminish because code usage increases
Avoid redundancyDon't rewrite what's already done
Lower error riskEventually help to improve existing code
Don't begin from scratchBuild on more and more consolidated code
Naming and legacy
Before 3.0, ejb were clumsy and complexYou were obliged to implement interfaces needed by the very same architecture
Rod Johnson writes J2EE development without EJB, releases first version of Spring Framework (2002)
EJB 2.x = J2EE
EJB 3.0 = Java EE 5, 3.1 = EE 6Java EE 6 Gets it Right, Rod Johnson's blog at http://blog.springsource.com/2007/07/03/java-ee-6-gets-it-right/
Distributed Application Frameworks
DCOM, COM+, WCF (Microsoft)http://msdn.microsoft.com/de-de/netframework/aa663324.aspx
Enterprise JavaBeans (Java)this presentation :)
http://java.sun.com/products/ejb/
CORBA (Object Management Group)a specification, not tied to a specific language
use IDL and language binding
http://www.omg.org/cgi-bin/doc?formal/04-03-12.pdf
The need for distributed components
type
myApp = class;
procedure ...
begin//do smthg very difficult
end
public partial class MyOwnApp
public Object myOwnComplexSolution(){ Object o = Helper.getMyComplexSolution;. . .
}
public class MyApp
public Object myComplexSolution() {//do smthg very
difficult
return Object;
public class MyVerySpecialApp
public void computeSmthg(){ Object o = MyApp.myComplexSolution() { }
Solutions
Copy and paste the algorithm
(Re)write the algorithm
Delegate the algorithm to the business expert dev team and make it available
Many solutions = many maintainers
Which is the right solution?
Make algorithm available cross platform
Solution
public partial class MyOwnApp
public Object myOwnComplexSolution(){ Object o = WS.myComplexSolution;. . .
}
public class MyVerySpecialApp{
public void computeSmthg(){ //look up for bean
//consume method }}
Java EE 5
ASpublic class MyApp{
public Object myComplexSolution() {//do smthg very
difficult
return Object;}}
Beantype
myApp = class;
procedure ...
begin//do smthg very difficult
end
Webservice
db
Improvements
By delegating to the business expert You obtain a business data assetNo redundacy
Data is expect to be as correct as possibleConsistent / semantic: data makes sense, it means smthg, because it is from the business expert domainExample:
Complete:
Solution's algorithm (~)
Define a remote interface
Write a Java class that implements that interfaceMake proper annotations (e.g. @Stateless )
May require entity beans, goto 2)
Test
Define an endpoint interface(you may use inheritance :) )
Make the proper annotations (e.g.@Webmethod)
Deploy
The need for distributed components
Application A
Application B
Application C
A possible (re) use case
GCA
BDPA
1 .queries for person
2. returns person
XMas
3. stores
4. change in person
4a. update
4b. inform
4c. update
4d. synch with
Data responsability
A possible (re) use case
GCA
BDPA
1. queries for person
2. returns UUID
EFIN
Schema
3. stores
4. change in person
5. updates
Data responsability
Component responsability
AU
Consequences
The semantic meaning of the database may changefrom health serviced people into general peopleAlthough in our case, people derived from GCA are probably a subset of health serviced people
The type of responsability changesfrom data responsability to component responsability
data quality now is a cross office issue!
Why we need 3 tier architecture
MonolithicClient(Database)
ServerUIBusiness ServicesData Services
Why we need 3 tier architecture
Decoupling UI logic from business logicOther components may use the logic as part of their process
Change business logic only in one place
'Slims' the client
By isolating business logic, many types of UI can use it
Decoupling business logic from persistence logicMakes data services exchangeable
Expose business logic as webservice makes it available cross platform
No doubt: it's more complex to write applications
Why we need 3 tier architecture
Business ServicesData Services
Business Services
Fat Client UI
Webservice
Business Services
Mobile UIWeb UI
Consequences
Develop components instead of spot solutionsJava development should use EJB 3.0 architectureDevelop beans that implement a remote interface
Make methods/beans cross-platform implementing a endpoint interface ( Webservice)
TODO: must find UI framework, Seam would be a candidate
.NET development uses CEE.NET frameworkComplete of Enterprise and UI Tier, many improvements wrt Java CEE
Delphi?
Enterprise JavaBeans
EJBEntity BeansMessage-Driven
BeansSession BeansStatefulStateless
Session Beans
Contain business logic (algorithms)Some of these methods should be made publicfor clients on other JVM: must be remotable
for clients on the same JVM: can be locable
Clients use Java Naming and Directory Interface (JNDI) to lookup bean
Stateless:Solutions in one shot give parameter, get result
Bean doesn't know about the client
Stateful:Solution needs multiple steps see shopping cart example
Bean knows about the client (state)
Session Bean example
package it.bz.provinz.server.i;
import javax.ejb.Remote;
@Remotepublic interface CFRemote{public boolean isValid(String cf);}
package it.bz.provinz.server.l;
import it.bz.provinz.server.i.CFRemote;
@Statelesspublic class CheckerBean implements CFRemote{
public boolean isValid(String cf){...}
Java Clients must know about the interface
if they are to use remote / local interface
Entity Beans
Just normal Java class that maps to a tableBut there's more to it on an advanced level :)
ID_PERNAMESURNAMEDOBCF
1PasqualeImbemba19.06.1970MBMPQL70H19Z112A
2JoePillow02.05.1984...
3.........
package it.bz.provinz.server.e;
import javax.persistence.*; @Entity@NamedQueries({@NamedQuery(name=Person.findByCF, query = SELECT p FROM Person p WHERE p.codiceFiscale =:cf)})@Table(name=PERSON)public class Person implements java.io.Serializable {
private static final long serialVersionUID = 1L;
@Column(name=ID_PER)private int id;@Column(name=NAME)private String name;@Column(name=SURNAME)private String surname;@Column(name=DOB)private Date dOb;@Column(name=CF)private String codiceFiscale;
Query logic is delegated to entity bean
We use EJB QL
Entity Beans
import javax.persistence.*; @Statelesspublic class CheckerBean implements CFRemote@PersistenceContext(unitName =JavaEE)private EntityManager eManager;
public boolean isValid(String cf){Query q = eManager.createNamedQuery(Person.findByCF);q.setParameter(cf, cf);if (q.getResultList().size() > 0)return true;return false;}
We use the query defined in theentity bean
We use the annotation
@PersistenceContextto inject a reference to EntityManager
References a deployment descriptor
(persistence.xml) in META-INF. This is the
persistence unit name
Relationships: OneToOne
ADDID (FK)PERSONIDSTREETZIPTOWNCOUNTRYADDRESS
@Entity@Table(name=PERSON)public class Person {@OneToOne@JoinColumn(name=ADD_ID)private Address adr;Beispiel Person mit Adresse: In dieser Variante mappen wir 1:1, Person hat den FK und wir legen fest, da eine Person 0/1 Adressen hat
Relationships: @OneToOne
PERID (PK)...PERSON@Entity@Table(name=PERSON)public class Person {@OneToOne@PrimaryKeyJoinColumnprivate Address adr;PERID (PK)STREETZIPTOWNCOUNTRYADDRESS
Beispiel Person mit Adresse: In diesem Fall benutzen wir den PK aus Person in der Tabelle Adresse. Vorteil: Wenn wir morgen nicht mehr 0/1, sondern 0/n Beziehung zwischen Person und Adresse einrichten mchten, brauchen wir der Table Adresse nur eine weitere Spalte mit einer ID und einen composite Key zwischen PERID(PK von Person) und der neuen Spalte zu machen (Unique constraint)
Relationships: @OneToOne
mappedBywhen we want to express a mutual relationship, i.e.a person might have at most one address, and an address belongs exactly to one person
one of the two entities is the relationship owner (the one that has the FK)
the other refers to the relationship owner
@Entity@Table(name=PERSON)public class Person {@OneToOne(mappedBy=per)private Address adr;@Entity@Table(name=ADDRESS)public class Address {@OneToOne@PrimaryKeyJoinColumnprivate Person per;
Relationships: @OneToMany
ORDID (PK)PERID (FK)...ORDERARTID (PK)ORDID (PK)QUANTPRICEORDERPOS
@Entity@Table(name=ORDER)public class Order {@OneToMany@JoinColumn(name=ORDID)private Collection orderPos = new ArrayList;Refers to the column of ORDERPOS
java.util.List, java.util.Map,
or java.util.Set may be used
Relationship: @ManyToOne
ORDID (PK)PERID (FK)...ORDERPERID (PK)...PERSON
@Entity@Table(name=ORDER)public class Order {@ManyToOne@JoinColumn(name=PERID)private Person person;again, if the relationship is mutual...
@Entity@Table(name=PERSON)public class Person {@OneToMany(mappedBy=person)private Collection orders = new ArrayList();
Relationship
@ManyToMany
FetchType.EAGER and FetchType.LAZY
CascadeTypeis optional, if set should be coherent with RI on db side
Entity Beans
ManagedEntityManager monitors the object = entity bean
Any change can lead to a database action
UnmanagedJust Java objects
EntityManager
Some history:Prior to 3.0, the definition of the peristence layer was part of the EJB-specification
Now, it's part of Java Persistence API 1.0 (in 3.0) JPA that's where the EntityManager comes in
Entity beans are just Java classes that contain meta information (annotations) with which the EM keeps aligned their attributes with the databaseAlignment occurs only when Entity Bean is assigned to the EntityMangerWe say that Bean is managed
EntityManager
When the bean is managed, the EntityManager will observe any attribute changes and decides, within the transaction, of the necessary steps to keep these changes aligned with the database
All entity beans and all relative changes managed by the EntityManager, are part of the so called PersistenceContext, which is typically (but not necessarily) tied to a transaction
EntityManager
To work with EM, we must define the scope of the persistence unit with a deployment descriptor (persistence.xml)
Each persistence unit is connected to a data source
java:DefaultDS