Příprava studijního programu Informatika je podporována projektem financovaným z Evropského sociálního fondu a rozpočtu hlavního města Prahy. Praha & EU: Investujeme do vaší budoucnosti Enterprise Java (BI-EJA) Technologie programování v jazyku Java (X36TJV) Katedra softwarového inženýrství Fakulta informačních technologií ČVUT v Praze Letní semestr 2010/2011, přednáška č. 4 Zdeněk Troníček, 2011
Agenda Enterprise Java Beans (EJB) 3.1 Java Persistence API (JPA) 2.0 2
Enterprise Java Beans 3.1 Session Beans (Entity Beans 2.1) Message Driven Beans Dependency Injection kontejner se postará o nastavení odkazu např. na jinou beanu 3
EJB aplikace client client Session Bean AutomaticTeller Entity TransactionLog ATMCustomer databáze client BranchTeller Account Customer 4
EJB container Container Life-Cycle Management Client Client Support Bean Resource Management 5
Session EJB Plain Old Java Object (POJO) bezestavové (@Stateless) stavové (@Stateful) singleton (@Singleton) (EJB 3.1) remote a local business interface no interface (EJB 3.1) 6
Implementace Business Interface import javax.ejb.local; @Local public interface HelloLocal { String sayhello(); @Local @Remote Bean import javax.ejb.stateless; 7 @Stateless @Stateful @Stateless public class HelloBean implements HelloLocal { public String sayhello() { return "Hello!";
Stateless Session EJB Container Pool Bean1 Client 1 1 EJB Object Banking 3 Bean2 2 4 Bean2 Client 2 8
Stateless Session EJB Life Cycle Does not exist 1. newinstance() 2. dependency injection 3. @PostConstruct callback @PreDestroy callback method Method-ready pool timeout callback 9
Stateful Session EJB Container Client1 Banking Bean1 Disc Client2 Banking Bean2 Client3 Banking Bean3 10
Stateful Session EJB Life Cycle dependency injection, business interface lookup Does not exist timeout 1. newinstance() @PreDestroy callback 2. dependency injection 3. @PostConstruct callback method Method-ready @Remove method or timeout @PrePassivate @PostActivate Passive 11 method
Singleton Session Beans Pouze jedna instance Lze stanovit pořadí inicializací (@DependsOn) Inicializace může být eager (@Startup) @Startup @Singleton( name = "A" ) @DependsOn( "B" ) public class ASessionBean { @Startup @Singleton( name = "B" ) public class BSessionBean { 12
Concurrency Management (1) @Singleton //@ConcurrencyManagement( // ConcurrencyManagementType.CONTAINER ) public class SingletonSessionBean { @Lock( LockType.READ ) public void dosomething() { @Lock( LockType.WRITE ) public void dosomethingelse() { 13
Concurrency Management (2) @Singleton @ConcurrencyManagement( ConcurrencyManagementType.BEAN ) public class SingletonSessionBean { public void dosomething() { synchronized(this) { public synchronized void dosomethingelse() { 14
Global JNDI Names java:global[/<app-name>]/<module-name>/<beanname>[!<fully-qualified-interface-name>] java:app/<module-name>/<bean-name>[!<fully-qualifiedinterface-name>] java:module/<bean-name>[!<fully-qualified-interface-name>] java:global/fooweb/foobean java:global/fooweb/foobean!com.acme.foo java:app/fooweb/foobean java:app/fooweb/foobean!com.acme.foo java:module/foobean java:module/foobean!com.acme.foo 15
Calendar Based Timer Service Anotace @Schedule s atributy: year, month, dayofmonth, dayofweek hour, minute, second timezone @Singleton public class ServiceBean { @Schedule( dayofweek = "Sun", hour = "2", minute = "30" ) public void cleandatabase() { 16
Asynchronní volání Metodu EJB lze volat asynchronně Návratovou hodnotou asynchronní metody je Future @Stateless public class MathSessionBean { @Asynchronous public Future<Integer> compute( Integer x, Integer y ) { Integer z = return new AsyncResult<Integer>( z ); Future<Integer> r = mathbean.compute( 20, 11 ); while (!r.isdone() ) { Integer i = r.get(); 17
Entities Entity <<Customer>> PK 100 <<Customer>> PK 101 Primary key 100 101 Customer Table... <<Customer>> PK 199 199 18
Entity @Entity public class Customer { @Id @Column(name = "IDENT") private Integer id; @Column(name = "JMENO", nullable = false) private String name; //public Customer() { public Integer getid() { return id; public void setid(integer id) { this.id = id;... @Entity public class Account { @Id private Integer id; private BigDecimal balance; //public Account() { public Integer getid() { return id; public void setid(integer id) { this.id = id;... Configuration by exception 19
Persistence Unit & Context Persistence Unit Persistence Context Lifetime: TRANSACTION EXTENDED Customer persistence. xml entity managers Account entity manager factory Customer id=2 Account id=2 Account id=3 Customer id=5 20
Entity Manager Java EE Java SE @PersistenceContext private EntityManager em; public Account openaccount( String owner ) { Account account = new Account(); account.setowner( owner ); em.persist( account ); return account; EntityManagerFactory emf = Persistence.createEntityManagerFactory( "pu1" ); EntityManager em = emf.createentitymanager(); em.gettransaction().begin(); em.persist(new Customer( 1, "Rumcajs" )); em.gettransaction().commit(); em.close(); emf.close(); 21
Entity Life Cycle new new persist() find() refresh() removed remove() persist() managed merge() detached persistence context ends 22
Vztahy mezi entitami One-to-one One-to-many Many-to-one Many-to-many unidirectional bidirectional Customer inverse side owning side Account 23
Unidirectional one-to-one owner @Entity public class Employee { @OneToOne private Car car; public Car getcar() { return car; public void setcar( Car car ) { this.car = car;... EMPLOYEE FK1 FK2 CAR 24
Bidirectional one-to-one owner @Entity public class Employee { @OneToOne private Car car;... @Entity public class Car { @OneToOne( mappedby= car mappedby="car" )) private Employee emp;... EMPLOYEE FK1 FK2 CAR 25
Unidirectional one-to-many owner @Entity public class Customer { @OneToMany private Collection<Account> accounts;... JPA 2.0: foreign key CUSTOMER C1 C2 CUSTOMER_ACCOUNT C1 C1 A1 A2 ACCOUNT A1 A2 unique constraint 26
Bidirectional many-to-one/one-to-many @Entity owner public class Employee { @ManyToOne private Department dep;... @Entity public class Department { @OneToMany( mappedby= dep mappedby="dep" )) private Collection<Employee> employees;... EMPLOYEE E1 FK1 E2 FK1 DEPARTMENT D1 D2 27
Unidirectional many-to-many @Entity owner public class Employee { @ManyToMany private Collection<Project> projects;... EMPLOYEE E1 E2 EMPLOYEE_PROJECT E1 E1 E2 P1 P2 P2 PROJECT P1 P2 28
Bidirectional many-to-many @Entity owner public class Employee { @ManyToMany private Collection<Project> ps;... @Entity public class Project { @ManyToMany( mappedby= ps mappedby="ps" )) private Collection<Employee> es;... EMPLOYEE E1 E2 EMPLOYEE_PROJECT E1 E1 E2 P1 P2 P2 PROJECT P1 P2 29
Mapování hierarchie tříd Vehicle id make Car color Motorcycle passengers jedna tabulka (SINGLE_TABLE) jedna tabulka pro každou třídu (JOINED) jedna tabulka pro každou neabstraktní třídu (TABLE_PER_CLASS) 30
Single Table per Class Hierarchy VEHICLE ID DTYPE MAKE 1 Car Škoda 2 Motorcycle Jawa COLOR černá NULL PASSENGERS NULL 2 @Entity @Inheritance( strategy = InheritanceType.SINGLE_TABLE ) @DiscriminatorColumn( name = "DTYPE" ) public abstract class Vehicle {... @Entity @DiscriminatorValue( "Car" ) public class Car extends Vehicle {... 31
Joined Subclass Strategy VEHICLE ID DTYPE MAKE 1 Car Škoda 2 Motorcycle Jawa CAR MOTORCYCLE ID COLOR ID PASSENGERS 1 černá 2 2 32
Table per Concrete Class CAR ID MAKE COLOR 1 Škoda černá MOTORCYCLE ID MAKE PASSENGERS 2 Jawa 2 33
Nalezení entity @Stateless public class VehicleManagerBean implements VehicleManagerLocal { @PersistenceContext private EntityManager em; public Vehicle findvehicle( Long id ) { return em.find( Vehicle.class, id id ); );... Polymorphism: id=1 Car id=2 Motorcycle 34
Query @Stateless public class VehicleManagerBean implements VehicleManagerLocal { @PersistenceContext private EntityManager em; public Collection<Vehicle> findallvehicles() { Query query = em.createquery( "SELECT v FROM Vehicle v" ); return query.getresultlist();... Java Persistence Query Language Polymorfizmus: výsledek může obsahovat instance různých tříd 35
Otázky & odpovědi tronicek@fit.cvut.cz