Download presentation
Presentation is loading. Please wait.
Published byReynold Dixon Modified over 8 years ago
1
EJB 3.0 Persistence Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0
2
Object-Relational Mapping Relational Databases are the most common way to store persistent data data is stored as a set of Relational Tables A mapping between Objects and data in Tables is needed programs create and use objects There is a multitude of Relational Database Management Systems (RDMS) the Java Database Connectivity (JDBC) API is a standard relational database access interface allows a consistent access across RDMSs
3
Object-Relational Mapping Clients Table Client String name Date birthdate Account account JDBC Common Mapping A Class corresponds to 1 or more Tables Class instances correspond to Rows in Tables Field values correspond to cells Accounts Table Mapping needs to maintain correspondance when saving instances and reading instances ends-up very complex and hard for maintainance
4
EJB 3.0 Persistence API High-level API for Object-Relational Mapping on top of JDBC Persistent entities manipulated are Plain Old Java Objects (POJO) refered to as entities correspondance to Relational Tables is ensured by the API frees away from lot of low level tasks
5
Entities Plain Old Java Object In-memory Java representation of persistent data loaded from storage with fields populated with the stored data can be modified in memory to change the value of data can be saved back (updates the database data) Uses Annotations introduced in Java SE 5.0 (J2SE 1.5.0)
6
Persistence Entity Example @Entity public class Customer { private Long id; private String name; private Address address; private Collection orders = new HashSet(); public Customer() {} @Id public Long getID() { return id; } protected void setID (Long id) { this.id = id; }... Annotated as “Entity” Getters/setters to access state @Id denotes primary key
7
Persistence Entity Example (Contd.)... // Relationship between Customer and Orders @OneToMany public Collection getOrders() { return orders; } public void setOrders(Collection orders) { this.orders = orders; } // Other business methods... }
8
Entities An entity class must declare a primary key using annotation @Id entity objects of the same class are uniquely identified by the primary key Access to the entity's persistent can be by direct field access or using JavaBean style of getters and setters An entity can add more methods (business methods)
9
Persistence Context Set of entity instances in which for any persistent entity identity there is a unique entity instance. Entity instances are managed within a persistence context by a particular Entity Manager. The scope of context can either be a transaction (e.g. a request), or an extended unit of work (e.g. a session)
10
Entity Manager Used to access database and control lifecycle of entities A Persistence Unit defines the set of entity types that can be managed by a given entity manager defines the set of all classes that are related or grouped by the application, and which must be collocated in their mapping to a single data store Two types of Entity managers Container-Managed Entity Manager Application-Managed Entity Manager
11
Entity Manager -API persist() - insert an entity into the DB remove() - remove an entity from the DB merge() - synchronize the state of detached entities refresh() - make sure the persistent state of an instance is synchronized with the values in the data store find() - find entities by their primary key flush() - immediately synchronize entity and DB
12
Entity Manager Persist Operation public Order createNewOrder(Customer customer) { Order order = new Order(customer); // Transitions new instances to managed. On the // next flush or commit, the newly persisted // instances will be inserted into the datastore. entityManager.persist(order); return order; }
13
Entity Manager Find and Remove Operations public void removeOrder(Long orderId) { Order order = entityManager.find(Order.class, orderId); // The instances will be deleted from the datastore // on the next flush or commit. Accessing a // removed entity has undefined results. entityManager.remove(order); }
14
Entity Manager Merge Operation public OrderLine updateOrderLine(OrderLine orderLine) { // The merge method returns a managed copy of // the given detached entity. Changes made to the // persistent state of the detached entity are // applied to this managed instance. return entityManager.merge(orderLine); }
15
Entity Manager Container-Managed Entity Manager The lifecycle of the Entity Manager is managed by the container Can be obtained by: Injection from container using @PersistenceContext From SessionContext using lookup() method
16
Entity Manager Container-Managed Entity Manager obtained by injection from Container public class... { /** Entity manager object, injected by container **/ @PersistenceContext private EntitityManager manager;... private Account findAccount(int accountNumber) { Account account = manager.find(Account.class,accountNumber); return account; }... } Instance is provided by Container
17
Entity Manager Container-Managed Entity Manager obtained from session context @PersistenceContext(name="persistence/logicalname",unitName="nameInPersistenceUnit") public class... { public void service ( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Context envCtx = new InitialContext().lookup("java:comp/env"); EntityManager em = (EntityManager) envCtx.lookup("persistence/logicalName");... Account account = manager.find(Account.class,accountNumber);... }... }
18
Entity Manager Application-Managed Entity Manager The lifecycle of the Entity Manager is managed by the application Entity Manager created using a EntityManagerFactory Entity Manager needs to be closed by application
19
Application-Managed Entity Manager public class RegistrationServlet extends HttpServlet { // EntityManagerfactory injection @PersistenceUnit private EntityManagerFactory emf; public void service ( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Entity Manager creation EntityManager manager = emf.createEntityManager();... Account account = manager.find(Account.class,accountNumber);... // close Entity Manager manager.close(); }... }
20
Entity Lifecycle
21
New: entity created in memory but not associated yet with a persistent entity in database Managed: entity has a persistent identity in the database and is associated with a persistent context. Detached: entity has a persistent identity but is no longer associated with the persistent context. Removed: entity is associated with a persistent context but has been scheduled for removal from the database.
22
Object-Relational Mapping Comprehensive set of annotations defined for mapping Relationships Joins Database tables and columns Database sequence generators ... Specified using standard description elements in a separate mapping file or within the code as annotations
23
Simple Mappings CUSTOMER IDNAMEC_RATING PHOTO @Entity(access=FIELD) @Id @Lob public class Customer { int id; String name; int c_rating; Image photo; }
24
public class Customer { int id; String name; int c_rating; Image photo; } Simple Mappings @Entity(access=FIELD) @Column(name=“CREDIT”) @Id @Lob CUSTOMER IDNAMECREDIT PHOTO
25
O/R Mapping Examples @Entity @Table(name="EMPLOYEE", schema="EMPLOYEE_SCHEMA") uniqueConstraints= {@UniqueConstraint(columnNames={"EMP_ID", "EMP_NAME"})} public class EMPLOYEE {... @Column(name="NAME", nullable=false, length=30) public String getName() { return name; } } @Version @Column("OPTLOCK") protected int getVersionNum() { return versionNum; } @ManyToOne @JoinColumn(name="ADDR_ID") public Address getAddress() { return address; }
26
Mapping Inheritance hierarchies Specifies Tables correspondence to Classes with sub-classing Single table All the classes in a hierarchy are mapped to a single table Root table has a discriminator column whose value identifies the specific subclass to which the instance represented by row belongs Joined subclass The root of the hierarchy is represented by a single table Each subclass is represented by a separate table that contains fields specific to the subclass as well as the columns that represent its primary key(s)
27
Inheritance Mapping Example @Entity @Table(name=”CUST”) @Inheritance(strategy=SINGLE_TABLE, discriminatorType=STRING, discriminatorValue=”CUST”) public class Customer {...} @Entity @Inheritance(discriminatorValue=”VCUST”) public class ValuedCustomer extends Customer{...}
28
Entity Relationships Models association between entities Supports unidirectional as well as bidirectional relationships Unidirectional relationship: Entity A references B, but B doesn't reference A Cardinalities One to one One to many Many to one Many to many
29
Entity Relationships One-to-one – exactly one entity related to another entity (e.g. Person and SIN Card) One-to-many – an entity is related to many other entities (e.g. Manager and Employee) Many-to-one – many entities related to a particular entity (e.g. Bank Account and Person) Many-to-many – many entities related to many entities (e.g. Student and Course)
30
Entity Relationships: Example Many to Many @Entity public class Project { private Collection employees; @ManyToMany public Collection getEmployees() { return employees; } public void setEmployees(Collection employees) { this.employees = employees; }... }
31
Cascading Behavior Cascading is used to propagate the effect of an operation to associated entities Cascading operations will work only when entities are associated to the persistence context If a cascaded operation takes place on detached entity, IllegalArgumentException is thrown Cascade=PERSIST Cascade=REMOVE Cascade=MERGE Cascade=REFRESH Cascade=ALL
32
Queries Entity Manager method find() returns a managed Entity from an item in the Database based on a provided primary key public static User findUser(EntityManager em,String id) { User u = em.find(User.class, id); return u; }
33
Queries Query object is used for other queries General steps for making queries with Query object obtain instance of Query from Entity Manager customize query object if necessary (e.g. setting query parameters, upper limit of result set size,...) execute query Queries can be expressed in EJB-QL: object query language using Query method createQuery(String query) SQL: standard Relational Database language using Query method createNativeQuery(String query)
34
Queries public static List findUsersByName(EntityManager em,String name) { // create EJB-QL query Query query = em.createQuery( "SELECT u FROM User u" + " WHERE u.NAME = :userName"); // customize query query.setParameter("userName",name); // run query List resultList = query.getResultList(); return resultList; }
35
Named Queries Queries that are defined in a static way possibility to invoke throughout the code provide a single point of modification @Entity @NamedQuery (name=”findThem”, queryString=”Select a FROM Account a”) public class Account implements Serializable {...}... public class.. // use of named query within persistence unit public List listAccounts() { Query query = manager.createNamedQuery(“findThem”); return query.getResultList(); }
36
Transactions Enable to group multiple operations into a single unit either the whole group succeed or the whole group fails if something goes wrong Transaction support is essential for safe, consistent Database updates UserTransaction provides interface for setting and controlling Transactions: begin() - begin a new transaction commit() - complete a transaction rollback() - abord a transaction and go back to initial state
37
Transactions public class LookupServlet extends HttpServlet { // injects a User Transaction object @Resource private UserTransaction utx;... public boolean addUser() { try { utx.begin(); User nuser = new User(); nuser.setUSER_ID(..); nuser.setNAME(...); nuser.setBIRTHDATE(...); manager.persist(nuser); utx.commit(); return true; } catch (Exception ex) { utx.rollback() } return false; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.