ejb - École mohammadia d'ingénieurs• stateless session beans – on server, you make...

68
EJB Karim Bouzoubaa Issam Kabbaj

Upload: others

Post on 07-Jul-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

EJB

Karim Bouzoubaa Issam Kabbaj

Page 2: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Problématique

•  Pour accéder aux données : –  Établir une connexion avec la BD –  Envoyer une requête –  Traiter la requête –  Assurer l'intégrité

•  Or : –  Nous voulons rester dans un monde Java –  Ne pas s'occuper de la connexion –  Na pas avoir à assurer l'intégrité

html jsp jdbc

table Objets java

4/27/14 EJB 2

Page 3: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Objectif •  Diviser

– Chacun parle un langage – Assurer les interfaces – Architecture n-tiers

client

html

http

Serveur web

jsp servlet

Serveur Application

EJB

BD

BEA Logic JBOSS

Apache IIS

Monde JAVA

4/27/14 EJB 3

Page 4: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Architecture JEE

4/27/14 EJB 4

Page 5: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Objectif •  Serveur web

– Avec le client : servlet-jsp/html – Avec le serveur d'application : Java

•  Serveur d'application

Serveur web

Serveur Application

EJB

Partie 1

Interface BD

Partie 2

Offre de services

BD

4/27/14 EJB 5

Page 6: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Objectif

•  Partie 1 : – ORM (Object Relational Mapping)

•  Assurer la connexion et conversion Objets Java / Modèle relationnel BD

•  Assurer l'intégrité et la persistance avec BD

–  Sous traité à des librairies (JPA: TOPLink, Hibernate, EclipseLink, …)

•  Partie 2 : –  Permet au client demandeur (1 jsp, 1 servlet, 1 prog java)

d'effectuer des requêtes par des appels Java et à retourner comme résultat des objets Java

4/27/14 EJB 6

Page 7: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Exemple

Serveur web

Serveur Application

Table Pays

Prog jsp: lister tous les

pays

… findAllPays() computeAVG() …

Service 1: findAllPays()

Service 1

accès Table Pays

Conversion en

objets Java

Service 2

Service 3

Liste

des

Objets

Pays

4/27/14 EJB 7

Page 8: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

EJB

•  Architecture permettant la création d'applications réparties

•  Spécification d'une architecture permettant la création d'applications distribuées –  2 versions

•  1.1 : la plus courante •  3.0 : la plus récente

•  Composant développé pour être exécuté sur un serveur d'EJB et appelé par un client distant –  Ne pas confondre avec un java bean qui est un

composant côté client

4/27/14 EJB 8

Page 9: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Objectifs des EJB

•  Rendre une application –  Facile à développer, à déployer et à administrer –  Indépendamment de la plate-forme permettant son exécution

•  Un EJB n'est pas spécifique à la plateforme dans laquelle il est utilisé

•  Fournir une plate-forme standard pour la construction

d'applications distribuées en Java

•  Simplifier l'écriture de composants serveurs

•  Portabilité

4/27/14 EJB 9

Page 10: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Benefits of EJB •  Encapsulating business logic

–  Business logic separated from control and presentation •  Remote access

–  Multiple apps on different servers can access EJBs •  Simplicity

–  Relatively easy to use compared to other remote-object systems

•  Broad vendor support –  JBoss, Oracle AS, WebLogic, WebSphere, Glassfish, etc.

•  Scalability –  Virtually all Java EE app servers support clustering, load

balancing, and failover

4/27/14 EJB 10

Page 11: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Types de Bean

•  Session Beans : contiennent la logique métier de l'application – Etat (state): données relatives au client

•  Stateful session bean •  Stateless session bean

•  Entity Beans : contiennent la logique de gestion des données persistantes

•  Message bean : contiennent la logique orientée message

4/27/14 EJB 11

Page 12: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Session Bean •  Fournit un service à un client •  Durée de vie limitée à celle du client •  Effectue des calculs ou des accès à une base de données •  Est non persistant (short-lived) •  Associé à un seul client •  Un flot d'exécution est créé pour

–  chaque appel de méthode •  stateless sessions bean (sans état) •  pas de donnée interne, inutile de le rendre passif, peut être partagé par

plusieurs clients –  plusieurs appels de méthodes en provenance du même client

•  Stateful sessions bean (avec état)

•  Détruit après un arrêt (ou une panne) du serveur EJB

4/27/14 EJB 12

Page 13: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Session à Stateless •  Stateless (sans état) à les attributs de l’EJB sont réinitialisées entre

chaque appel même s’il s’agit du même client •  Sont spécialement pensés pour être robustes et fiables lorsqu’il y a

beaucoup d’appels en concurrence

•  Lorsqu’un client appelle l’EJB, une instance de ce dernier sert le client, puis,

retourne dans le pool d’EJB (cette dernière est donc prête à être réutilisée pour un autre client)

•  A utiliser le plus souvent possible (par rapport aux Stateful) à cycle de vie

4/27/14 EJB 13

Page 14: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Session beans •  Stateless session beans

–  On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless)

•  Ordinary Java object with ordinary methods that use ordinary Java objects as arguments and return types

•  No state (instance vars) maintained between method calls –  Client uses InitialContext.lookup("name") to get ref.

•  Client makes normal method calls (data serialized on net.)

•  Stateful session beans –  Mark POJO with @Stateful instead of @Stateless –  Mark special method with @Remove –  Client does similar lookup and method calls, but needs to call the

special method when done. •  State (instance vars) maintained until that method called

4/27/14 EJB 14

Page 15: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Stateless Session Beans : Approach •  Define an interface

–  Mark with @Remote •  For access from other servers or from projects on same

server –  Mark with @Local

•  To only allow access from projects on same server (default)

•  Create a class that implements interface –  Mark with @Stateless for server’s default JNDI

mapping –  Mark with

@Stateless(mappedName="SomeJndiName ») –  (Java Naming and Directory Interface)

4/27/14 EJB 15

Page 16: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Interface Means that you can use InitialContext to access from either same server or remote machine.

Remote client will pass in normal arguments and get normal return values. Behind the scenes, however, data will be serialized and sent across network.

4/27/14 EJB 16

Page 17: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Class that Implements Interface If you just use @Stateless, remote clients need to use serverspecific JNDI name. If you are using Glassfish only (or JBoss only), this is fine. But if you want to deploy the same app to multiple servers and not change the client code at all, it simplifies things to use a common JNDI name via @Stateless(mappedName="JNDI-Name")

4/27/14 EJB 17

Page 18: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Remote Standalone (Desktop) Client mappedName given in @Stateless annotation

Used like normal object. Behind the scenes, however, arguments and return value are sent across network.

4/27/14 EJB 18

Page 19: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Remote Client : jndi.properties

•  Notes –  Created text file called “jndi.properties” in src folder

•  For Glassfish org.omg.CORBA.ORBInitialHost=localhost

•  Output –  Small lucky number:4,46 –  Medium lucky number:20,03 –  Big lucky number: 431,26

Change this hostname if app server is on different host than client.

4/27/14 EJB 19

Page 20: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Client •  Clients must also define (have a copy - share) the interface

•  Clients find the bean via JNDI –  Client Java code doesn’t even know the machine on which the bean resides

•  Clients use the bean like a normal POJO –  But arguments and return values are sent across network –  So, custom classes should be Serializable

•  Core client code InitialContext context = new InitialContext();

InterfaceName bean = (InterfaceName)context.lookup("JNDI-Name"); NumberService bean = (NumberService)context.lookup("NumberServiceJNDIName"); NumberService bean = (NumberServiceImplementation)context.lookup("NumberServiceJNDIName");

4/27/14 EJB 20

Page 21: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Deploying

–  Does not need to run on same machine as EJB Project. –  Standalone (desktop) clients don’t need to be deployed

to any app server; they can just have a “main” method.

–  Web apps should be deployed to a Java EE 5 app server

4/27/14 EJB 21

Page 22: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Remote Web Client (Servlet)

4/27/14 EJB 22

Page 23: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Output

4/27/14 EJB 23

Page 24: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

DEMO

Page 25: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Using @EJB to Access Local Beans •  Use @EJB before instance variable

–  Bean will be automatically instantiated and assigned. Eg: •  @EJB private SomeService myService;

•  Useful for –  One EJB that uses another EJB as part of its logic

•  Always good idea since EJBs are usually together –  Multiple Web apps that use the same business logic

•  Simpler, but Web app can’t move to remote server

•  Restrictions –  Before instance variables, not local variables. –  Both classes must be part of same EAR on same server

•  In Eclipse, all classes in a single EJB project satisfy this •  If you use an EJB project (EJBs) and Dynamic Web projects (classes

that use the EJBs), you must choose « Add project to an EAR » and specify same one.

4/27/14 EJB 25

Page 26: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

EJB Interface

4/27/14 EJB 26

Page 27: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

EJB Class that Implements Interface Declare the interface type (NumberService), not the concrete type (NumberServiceImplementation).

4/27/14 EJB 27

Page 28: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Remote Client (Servlet)

Looks up remote EJB the normal way. That remote EJB uses @EJB to access a local bean. If this Web app were always part of the same EAR on the same app server, then this Web app could also use @EJB to access beans. But having the Web app use InitialContext is more flexible because it allows for the possibility of the Web app later moving to another server without changing any code.

4/27/14 EJB 28

Page 29: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Output

4/27/14 EJB 29

Page 30: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

EXERCISE WITH DESKTOP APPLICATION

Page 31: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Session à Stateful •  Stateful (avec état) => les attributs de l’EJB sont sauvegardés durant toute la session

•  Lorsqu’un client appelle l’EJB, une instance de ce dernier est créée, puis sert le client. Cette instance reste disponible pour les futurs appels de ce client uniquement. Cette instance sera détruite à la fin de la session (timeout ou appel à une méthode portant l’annotation @Remove)

•  S’il y a trop d’instances d’un EJB en mémoire, ces dernières peuvent être sorties de la mémoire de travail. Elles passent ainsi en mode passif (= sauvées sur disque => tous les attributs doivent être sérialisables = types implémentant l’interface Serializable)

4/27/14 EJB 31

Page 32: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Stateful Session Beans : Approach •  Define an interface

–  Mark with @Remote •  For access from other servers or from projects on same

server –  Mark with @Local

•  To only allow access from projects on same server (default)

•  Create a class that implements interface –  Mark with @Stateful for server’s default JNDI

mapping –  Mark with

@Stateful(mappedName="SomeJndiName") –  Mark a method with @Remove

•  When called, server terminates session and gc’s instance

4/27/14 EJB 32

Page 33: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

EJB Interface

4/27/14 EJB 33

Page 34: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

EJB Class that Implements Interface

Client will call this method first to set up the state of the bean. Then the client will repeatedly access the getBlah methods to access information related to the state. When done, the client will call removeList

Remote client will do Context.lookup("cool- number-list") and cast it to FancyList

4/27/14 EJB 34

When client calls this method, session is broken and bean instance is eligible for garbage collection

Page 35: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Remote Client (Servlet)

Sets up state that will be used in the JSP page

JSP page (MVC approach) uses state of the EJB

Tells remote app server we are done with stateful EJB

4/27/14 EJB 35

Page 36: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Remote Client (JSP)

4/27/14 EJB 36

Page 37: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Remote Client (Input Form)

4/27/14 EJB 37

Page 38: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Remote Client : Results

4/27/14 EJB 38

Page 39: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Développer des sessions Beans

•  Stateful vs Stateless – Utiliser un bean session avec état (stateful) si :

•  Le bean enregistre des données d ’un seul c l ient particulier(comme une session d’un navigateur Web)

•  Le bean enregistre des données pendant la durée d’appel de plusieurs invocations de méthodes

•  L’état du Bean représente l’état de l’interaction entre le client et le Bean

•  Le Bean doit conserver de l’information entre deux invocations du client

•  Dédié à un client pendant toute sa dur de vie

•  Le même Bean est utilisé pour servir tous les appels du même client

4/27/14 EJB 39

Page 40: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Développer des sessions Beans •  Utiliser un bean session sans état (stateless) si :

–  Le bean n’enregistre pas des données d’un seul client

–  le bean existe pour un appel de méthode unique

–  le bean est utilisée pour extraire des données d'une base de données

–  Pour des tâches génériques

–  Pour consulter en lecture seule des données persistantes

–  Efficaces et faciles à implémenter

–  Les données sont passées comme paramètres de la méthode

4/27/14 EJB 40

Page 41: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Summary

•  Stateless session beans –  Interface: mark with @Remote –  Class: mark with @Stateless(mappedName="blah")

•  Stateful session beans –  Mark class with @Stateful instead of @Stateless –  Mark a method with @Remove

•  Session bean clients InitialContext context = new InitialContext(); InterfaceType var = (InterfaceType)context.lookup("blah"); var.someMethod(args); –  For stateful beans, call specially marked method when done –  Need jndi.properties specific to server type

•  Local access to beans @EJB private InterfaceType var;

4/27/14 EJB 41

Page 42: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Entity Bean •  Ce sont des objets qui savent se mapper

avec une base de données •  Ils servent à représenter sous forme d'objets

des données situées dans une base de données –  Le plus souvent un objet = une ou plusieurs

ligne(s) dans une ou plusieurs table(s) •  Accepte les accès multiples effectués par

plusieurs clients •  Utile pour gérer les accès concurrents à des

données persistantes

4/27/14 EJB 42

Page 43: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Persistance par mapping objet/BD relationelle

4/27/14 EJB 43

Page 44: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Entity Bean •  C’est une classe java « normale » (POJO) avec des attributs,

des accesseurs, des modifieurs, etc.

•  On utilisera les annotations (méta-données) ou « attributs de code » pour indiquer le mapping, la clé primaire, etc.

–  Clé primaire = un objet sérializable, unique pour chaque instance. C'est la clé primaire au sens SQL

•  On manipulera les données de la BD à l’aide des EntityBeans + à l’aide d’un PERSISTENT MANAGER (PM)

•  Le PM s’occupe de tous les accès disque, du cache, etc.

–  Lui seul contrôle quand et comment on va accéder à la BD, c’est lui qui génère le SQL, etc.

4/27/14 EJB 44

Page 45: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Annotation @Entity •  L’annotation @Entity définit le bean comme étant de

type entité •  Le bean doit posséder au moins un constructeur par

défaut et devra hériter de l’interface Serializable afin d’être utilisable à travers le réseau pour la gestion de la persistance

•  On peut spécifier deux méthodes différentes pour la gestion de la persistance au moyen de l’option access : –  @Entity(access=AccessType.FIELD) permet d’accéder

directement aux champs à rendre persistant –  @Entity(access=AccessType.PROPERTY) oblige le

fournisseur à utiliser les accesseurs

4/27/14 EJB 45

Page 46: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Clé primaire •  La clé primaire peut-être simple ou composée et doit être déclarée avec

l’annotation @Id –  Par exemple, pour obtenir une clé qui s’incrémente automatiquement :

•  @Id •  @GeneratedValue(strategy = GenerationType.AUTO or GenerationType.IDENTITY)

•  Pour les clés composées, il faut respecter certains principes : –  La classe de la clé primaire doit être public et posséder un constructeur sans arguments. –  Si l’accès est de type PROPERTY, la classe peut-être soit de type public soit de type protected.

–  La classe doit être sérialisable (implémenter Serializable). –  Implémentation des méthodes equals() et hashCode(). –  Si la clé primaire est mappée à de multiples champs ou propriétés, les noms des champs de cette clé

doivent être les mêmes que ceux utilisés dans le bean entité.

•  Les annotations permettent d’effectuer le mapping objet/relationnel et la gestion des relations entre les entités

4/27/14 EJB 46

Page 47: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Class Entity

4/27/14 EJB 47

La classe = POJO,

Sérializable,

Un attribut = la clé primaire

C’est tout !

Page 48: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Fichier persistence.xml

4/27/14 EJB 48

Page 49: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Class Stateless Session

4/27/14 EJB 49

•  Ce session bean est stateless,

•  Utilise un EntityManager,

•  Sert à envoyer des requêtes JPQL,

•  Méthode persist(entity) pour créer une nouvelle entrée (insert)

•  Le reste passe par des appels de méthodes classiques de l’entity bean.

Page 50: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Class Stateless Session

4/27/14 EJB 50

Page 51: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Client

4/27/14 EJB 51

Page 52: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Client

4/27/14 EJB 52

Page 53: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Main

4/27/14 EJB 53

Page 54: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Annotations utilisés •  Lors de la création d’un bean

entité, il faut effectuer le mapping de tous ses champs.

•  @ T a b l e d é f i n i t l a t a b l e correspondant à la classe, elle prend en argumant le nom de la table.

•  Un mapping par défaut intervient l o r s q u ’ a u c u n e a n n o t a t i o n précède le champ : @Basic spécifie ce comportement.

@Entity(access=accessType.FIELD) @Table(name="PAYS") public class Pays implements Serializable {

@Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Basic private String nom; public Pays() { } public Pays(String nom) {

this.nom = nom; } public int getId() {

return id; }

}

4/27/14 EJB 54

Page 55: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Annotations utilisés •  On peut faire correspondre une valeur à un champ spécifique de la base de données en utilisant

l’annotation @Column et des options comme name qui spécifie le nom de la colonne, ou des options pour définir si champ peut être nul, …

@Column(name="DESC", unique=true, nullable=false, length=32) public String getDescription() {

return description; }

•  Il existe les relations OneToOne , OneToMany , ManyToOne , ManyToMany (définies par les annotations correspondantes). Dans ces cas, il ne faut pas oublier de spécifier les colonnes faisant les jointures.

@ManyToOne(optional=false) @JointColumn(name = "CLIENT_ID", nullable = false, updatable = false) public Client getClient (){

return client; } @JoinTable(name = "Mat_Prof", joinColumns = { @JoinColumn(name = "id_prof", referencedColumnName = "id_prof")}, inverseJoinColumns = { @JoinColumn(name = "id_mat", referencedColumnName = "id_mat")}) @ManyToMany private Collection<Matieres> matieresCollection;

4/27/14 EJB 55

Page 56: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

EntityManager •  Les beans entités se manipulent par l’intermédiaire d’un

EntityManager.

•  Cet EntityManager peut être obtenu à partir d’un Bean Session par injection de dépendance.

@Stateless public class EmployeeManager{ @PersistenceContext(unitName = "EmploiePU") EntityManager em; public void updateEmployeeAddress (int employeeId, Address address) {

//Recherche d’un bean Employee emp = (Employee) em.find("Employee", employeId); emp.setAddress (address);

} }

4/27/14 EJB 56

Page 57: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

•  This interface is used for interacting with the persistence context.

•  This interface is essential for database access and control, as it defines several methods for working with entity instances.

Create an Entity Bean Class

4/27/14 EJB 57

Page 58: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

• The Interface Methods •  The EntityManager interface defines several methods that you can use to work with entity instances.

• Some of the vital methods that you need to be aware of are the database management methods.

Create an Entity Bean Class

Method Description

find() Searches a table based on the primary key for a particular record.

remove() Removes the instance of an entity.

persist() Makes the instance of an entity managed and persistent.

4/27/14 EJB 58

Page 59: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Modèle global

4/27/14 EJB 59

Page 60: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Exemple avec Produit

•  Projet complet –  BD (table produit) –  EJB-Model

•  entite ejb •  session ejb

–  Servlet-Control –  Jsp-View

4/27/14 EJB 60

Page 61: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Exemple avec Produit

4/27/14 EJB 61

Page 62: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Exemple avec Produit

4/27/14 EJB 62

Page 63: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Exemple avec Produit

4/27/14 EJB 63

Page 64: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Exemple avec Produit

4/27/14 EJB 64

Page 65: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Exemple avec Produit

4/27/14 EJB 65

Page 66: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Exemple avec Produit

4/27/14 EJB 66

Page 67: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Exemple avec Produit

4/27/14 EJB 67

Page 68: EJB - École Mohammadia d'ingénieurs• Stateless session beans – On server, you make interface (marked with @Remote) and POJO that implements it (marked with @Stateless) • Ordinary

Liens utiles

•  http://netbeans.org/kb/docs/javaee/ecommerce/entity-session.html •  J2EE Specification

–  Java.sun.com/products/j2ee •  Enterprise Java Beans Specification 1.1 et 2.0

–  Java.sun.com/products/ejb •  Mastering Enterprise JavaBeans and the Java 2 Platform

Enterprise Edition – Ed Roman – Wiley Computer publishing 1999 •  www.theserverside.com •  java.sun.com/j2ee/tutorial •  www.jboss.org (serveur Open Source) •  Support de cours de Didier Donsez (université de Valenciennes) •  J2EE blueprints (java.sun.com) •  Mastering Enterprise JavaBeans II – Ed Roman -

(www.theserverside.com)

4/27/14 EJB 68