1 / 36

Entity Beans

Entity Beans. Lightweight persistence object Represents a table in a relational database An instance represents a row in the table Persistent state is the persistent fields or properties of the class

garvey
Download Presentation

Entity Beans

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Entity Beans • Lightweight persistence object • Represents a table in a relational database • An instance represents a row in the table • Persistent state is the persistent fields or properties of the class • Object/relational annotations are used to map entities and entity relations to the data in the database

  2. Entity Class Rules • The class must be annotated with the javax.persistence.Entity annotation. • The class must have a public or protected, no-argument constructor. The class may have other constructors. • The class must not be declared final. No methods or persistent instance variables must be declared final. • If an entity instance is passed by value as a detached object, such as through a session bean's remote business interface, the class must implement the Serializable interface. • Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes. • Persistent instance variables must be declared private, protected, or package-private, and can only be accessed directly by the entity class's methods. Clients should access the entity's state through accessor or business methods.

  3. Persistent Variable Types • Java Primitive Types • java.lang.String • Other serializable types • Wrappers of the java primitive types • BigInteger, BigDecimal, Date, Calendar, Time, TimeStamp, byte[], Byte[], char[], Character[] • User defined serializable types • Enumerated types • Other entities or collections of entities • Embeddable Classes

  4. Entity Bean Rules • All fields not annotated as @Transient (import javax.persistence.Transient) will be persisted • Collection interfaces may be used • java.util.Collection, java.util.Set, java.util.List, java.util.Map

  5. Entity Bean Properties • Follow Java Bean property rules • Getter Type getProperty() • Setter void setProperty(Type p) • May also use collection types • Can also use generics • Set<PhoneNumber> getPhoneNumbers() • void setPhoneNumbers(Set<PhoneNumber> nums)

  6. Entity Primary Keys • Each entity must have a primary key • May be simple or composite • Simple primary keys • use the javax.persistence.Id annotation to denote the primary key property or field. • Composite primary keys • must correspond to either a single persistent property or field, or to a set of single persistent properties or fields. • Defined in a primary key class • Denoted using javax.persistence.EmbeddedId and javax.persistence.IdClass

  7. Example Entity Bean import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="WEB_BOOKSTORE_BOOKS") public class Book implements Serializable { private String bookId; private String title;

  8. Example Entity Bean public Book() { } public Book(String bookId, String title, ...) { this.bookId = bookId; this.title = title; ... } @Id public String getBookId() { return this.bookId; }

  9. Example Entity Bean public String getTitle() { return this.title; } ... public void setBookId(String id) { this.bookId=id; } public void setTitle(String title) { this.title=title; } ... }

  10. Entity Primary Keys • The primary key, or the property or field of a composite primary key, must be one of the following Java language types: • Java primitive types • Java primitive wrapper types • java.lang.String • java.util.Date (the temporal type should be DATE) • java.sql.Date • Floating point types should never be used in primary keys. • If you use a generated primary key, only integral types will be portable.

  11. Entity Primary Keys • A primary key class must meet these requirements: • The access control modifier of the class must be public. • The properties of the primary key class must be public or protected if property-based access is used. • The class must have a public default constructor. • The class must implement the hashCode() and equals(Object other) methods. • The class must be serializable.

  12. Entity Primary Keys • Primary key class requirements (continued): • A composite primary key must be represented and mapped to multiple fields or properties of the entity class, or must be represented and mapped as an embeddable class. • If the class is mapped to multiple fields or properties of the entity class, the names and types of the primary key fields or properties in the primary key class must match those of the entity class.

  13. Entity Primary Key Class public final class LineItemKey implements Serializable { public Integer orderId; public int itemId; public LineItemKey() {} public LineItemKey(Integer orderId, int itemId) { this.orderId = orderId; this.itemId = itemId; }

  14. Entity Primary Key Class public boolean equals(Object otherOb) { if (this == otherOb) { return true; } if (!(otherOb instanceof LineItemKey)) { return false; } LineItemKey other = (LineItemKey) otherOb; return ( (orderId==null?other.orderId==null: orderId.equals(other.orderId)) && (itemId == other.itemId) ); }

  15. Entity Primary Key Class public int hashCode() { return ( (orderId==null?0:orderId.hashCode()) ^ ((int) itemId) ); } public String toString() { return "" + orderId + "-" + itemId; } }

  16. Example Entity Bean @IdClass(order.entity.LineItemKey.class) @Entity public class LineItem { @Id public int getItemId() { return itemId; } @Id @Column(name="ORDERID", nullable=false, insertable=false, updatable=false) public Integer getOrderId() { return orderId; } ... }

  17. Multiplicity in Entity Relationships • Each persistent property or field that is a reference to another Entity must be annotated • One-to-one • javax.persistence.OneToOne annotation • One-to-many • javax.persistence.OneToMany annotation • Many-to-one • javax.persistence.ManyToOne annotation • Many-to-Many • javax.persistence.ManyToMany annotation

  18. Direction of Entity Relationships • The direction of a relationship can be either bidirectional or unidirectional • Unidirectional • Only one Entity has a member reference to the other • Bidirectional • Both Entities have member references to each other • The side that doesn’t contain the foreign key must use the mappedBy element of the relationship annotation

  19. Cascade Deletes • Entities that use relationships often have dependencies on the existence of the other entity • Example: Item is part of an order. If the order is deleted, the Item should also be deleted. • Use cascade=REMOVE in @OneToOne and @OneToMany relationships @OneToMany(cascade=REMOVE, mappedBy="customer") public Set<Order> getOrders() { return orders; }

  20. Managing Entity Beans • Entity Beans are managed using an EntityManager • used to add, find, and delete entity beans • An EntityManager may be injected into a EJB Session Bean • unitName must match name in persistence.xml import javax.ejb.*; import javax.persistence.*; import javax.transaction.NotSupportedException; public class BookDBAO { @PersistenceContext(unitName="books") private static EntityManager em; ...

  21. Creating Entities • Use the new method to construct the entity • Persist the entity to the database Part part = new Part(partNumber, revision,description, revisionDate,specification,drawing); em.persist(part);

  22. Accessing Data from the Database public Book getBook(String bookId) throws BookNotFoundException { Book requestedBook = em.find(Book.class, bookId); if (requestedBook == null) { throw new BookNotFoundException( "Couldn't find book: " + bookId); } return requestedBook; }

  23. Setting Entity Relationships • Once you have the object, just use it. PartKey pkey = new PartKey(); pkey.partNumber = partNumber; pkey.revision = revision; Part part = em.find(Part.class, pkey); VendorPart vendorPart = new VendorPart(description, price,part); em.persist(vendorPart); Vendor vendor = em.find(Vendor.class, vendorId); vendor.addVendorPart(vendorPart); vendorPart.setVendor(vendor);

  24. public void buyBook(String bookId, int quantity) throws OrderException { try { Book requestedBook = em.find(Book.class, bookId); if (requestedBook != null) { int inventory = requestedBook.getInventory(); if ((inventory - quantity) >= 0) { int newInventory = inventory - quantity; requestedBook.setInventory(newInventory); } else { throw new OrderException("Not enough of " + bookId + " in stock to complete order."); } } } catch (Exception ex) { throw new OrderException("Couldn't purchase book: " + bookId + ex.getMessage()); } }

  25. Acessing Data from the Database public List getBooks() throws BooksNotFoundException { try { return em.createQuery( "SELECT bd FROM Book bd ORDER BY bd.bookId") .getResultList(); } catch(Exception ex) { throw new BooksNotFoundException( "Could not get books: " + ex.getMessage()); } }

  26. EJB Query Language • An EJB QL query has six clauses • SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY • SELECT and FROM are required • EJB QL ::= select_clause from_clause [where_clause][groupby_clause] [having_clause][orderby_clause]

  27. EJB Query Language • SELECT - defines the types of the objects or values returned by the query • FROM - defines the scope of the query • WHERE - conditional expression restricting the objects or values returned • GROUP BY - groups results according to a set of properties • HAVING - used with the GROUP BY to further restrict results • ORDER BY - sorts the objects or values

  28. EJB Query Language • A Basic Select Query • SELECT p FROM Player AS p • Elimination of duplicate values • SELECT DISTINCT p FROM Player p WHERE p.position = :position • :identifier - denotes an input parameter • Set input parameters using the Query.setNamedParameter method • The IS EMPTY expression • SELECT p FROM Player p WHERE p.teams IS EMPTY

  29. EJB Query Language • The BETWEEN expression • SELECT DISTINCT p FROM Player p WHERE p.salary BETWEEN :lowerSalary AND :higherSalary • Comparison Operators • SELECT DISTINCT p1 FROM Player p1, Player p2 WHERE p1.salary > p2.salary AND p2.name = :name

  30. Using Named Queries • Named queries are useful when using the same query many times. • @NamedQuery(name="findAllOrders",query="SELECT o FROM Order o") • List orders = em.createNamedQuery( "findAllOrders").getResultList(); • Best use is with named parameters • @NamedQuery(name="PartPricePerVendor",query="SELECT SUM(vp.price) " +"FROM VendorPart vp " +"WHERE vp.vendor.vendorId = :id") • return (Double) em.createNamedQuery("PartPricePerVendor") .setParameter("id", vendorId).getSingleResult();

  31. Removing Entities • Use the EntityManager.remove method • Order order = em.find(Order.class, orderId); em.remove(order);

  32. EJB Query Language • Also provides UPDATE and DELETE • update_statement :: = update_clause [where_clause] delete_statement :: = delete_clause [where_clause] • Where clause follows the same rules as with the SELECT statement delete_clause ::= DELETE FROM abstract_schema_name [[AS]identification_variable] update_clause ::=UPDATE abstract_schema_name [[AS]identification_variable] SET update_item {, update_item}* update_item ::= [identification_variable.] {state_field |single_valued_association_field} = new_value

  33. Bulk Updates public void updateBreedName (String oldbreed, String newbreed) { // I can't get @NamedQuery to work right now // @NamedQuery(name="ChangeBreed", // query="UPDATE Animal a “ + // “SET a.breed = :newbreed “ + // “WHERE a.breed = :oldbreed") // Query q = em.createNamedQuery("ChangeBreed"); Query q = em.createQuery("UPDATE Animal a” + “ SET a.breed = :newbreed WHERE a.breed = :oldbreed"); q.setParameter("newbreed", newbreed); q.setParameter("oldbreed", oldbreed); q.executeUpdate(); }

  34. Transactions • Used to ensure updates are processed in their entirety • Managed through a UserTransaction object • Use resource injection to get an instance • Transaction control • utx.begin(), utx.commit(), utx.rollback()

  35. @Resource UserTransaction utx; ... try { utx.begin(); bookDBAO.buyBooks(cart); utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch (Exception exe) { System.out.println( "Rollback failed:” + exe.getMessage()); } ...

More Related