Introduction to Entities

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

JBoss Seam: Contextual Components Jason Bechtel
Entities and Persistence. Entity Beans Topics to be Covered: Entities are POJOs Managed/Unmanaged Entities Persistence Unit EntityManager Basic Relational.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
ECE122 L6: Problem Definition and Implementation February 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation.
1 Introduction to CS Agenda Syllabus Schedule Lecture: the management of complexity.
1 Lecture 18 George Koutsogiannakis/Spring 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
The Java Persistence API Edel Sherratt. Contents Revisit applications programming Using Java Persistence API.
Rice KRAD Data Layer JPA Design Eric Westfall July 2013.
CSE446 S OFTWARE Q UALITY M ANAGEMENT Spring 2014 Yazılım ve Uyguluma Geliştirme Yöneticisi Orhan Başar Evren.
Towards Bboogle 3.0.0: a Technical Walkthrough Patricia Goldweic Sr. Software Engineer AR&T, Northwestern University Brian Nielsen Manager, Faculty Support.
Agenda What is Hibernate Spring Integration Questions Overview
Maven for building Java applications By Nalin De Zoysa
1 Lecture 17 George Koutsogiannakis/SUMMER 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
1 The Seven Relationship Types Seven types of relationships can exist between entity beans. There are four types of cardinality: one-to- one, one-to-many,
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
Data Access Patterns Some of the problems with data access from OO programs: 1.Data source and OO program use different data modelling concepts 2.Decoupling.
Entity Beans BMP Celsina Bignoli
Introduction to Accounting Information Systems
IS-907 Java EE JPA: Simple Object-Relational Mapping.
1 Stateful Session Beans Stateless Session Beans Michael Brockway Sajjad Shami Northumbria University School of Computing, Engineering & Information Sciences.
EJB 3.0 Persistence Sang Shin Java Technology Architect
EJB Framework.  As we know, EJB is the center of the J2EE architecture that provides a sturdy framework for building enterprise applications. The major.
JBoss Seam Presented by Andy Nguyen Truc Pham. What is JBoss Seam? Created by Gavin King Created by Gavin King A lightweight framework for Java EE 5.0.
CS 157B: Database Management Systems II February 4 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager.
CET203 SOFTWARE DEVELOPMENT Session 1A Revision of Classes.
1 Mapping Persistent Objects Entities represent data in the database, so changes to an entity bean result in changes to the database. That's ultimately.
EJB 3.0 Persistence Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0.
1 Architectural Overview For application developers, assembling enterprise beans requires little or no expertise in the complex system-level issues that.
Centre for Computer Technology ICT214 Object Oriented Design and Programming Week 02 – Classes, Objects, Instances Richard Salomon and Umesh Patel Centre.
1 Persistence in Java Enterprise Container Managed Persistence Application Managed Persistence Michael Brockway Sajjad Shami CG0165: Advanced Applications.
Java Data Persistence Using Hibernate Jack Gardner October 2004.
Fall CIS 764 Database Systems Engineering L7. ADF + EJB Context: Oracle Application Development Framework …but … only EJB.
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA ‏ Visibility Control.
MCS 270 Spring 2014 Object-Oriented Software Development.
A U.S. Department of Energy Office of Science Laboratory Operated by The University of Chicago Argonne National Laboratory Office of Science U.S. Department.
Middleware Technology (J2EE/EJB) Entity Bean (JBoss EJB 3.0 tutorial)
Topic : Hibernate 3:Advanced ORM Kaster Nurmukan.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Session Beans Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0.
The Java Persistence API ©SoftMoore ConsultingSlide 1.
Java Persistence API part 1 INFORMATICS ENGINEERING – UNIVERSITY OF BRAWIJAYA Eriq Muhammad Adams J
v110912Java Persistence: EntityManager2 Overview Earlier versions of EJB Specification defined the persistence layer –javax.ejb.EntityBean Java EE 5 moved.
Java Persistence API (JPA) Relationships. Kinds of relationships UML associations and aggregations (ER non- identifying relationships, shared semantics)
Classes, Interfaces and Packages
Java Programming: Advanced Topics 1 Enterprise JavaBeans Chapter 14.
IS-907 Java EE Introduction to JPA. Java Persistence API A framework for using relational databases in Java programs mapping between tables and classes,
Classes CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Hibernate Thuy, Le Huu. Pentalog VN. Agenda Hibernate Annotations Improving performance – Lazy loading – Fetching Strategies – Dynamic insert, dynamic.
1 Entity Callbacks and Listeners When you execute EntityManager methods like persist( ), merge( ), remove( ), and find( ), or when you execute EJB QL queries,
14 Copyright © 2004, Oracle. All rights reserved. Achieving State Management in the Business Tier.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA (I) Chengyu Sun California State University, Los Angeles.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
Hibernate Annotation 李日貴 (jini) jakarta99 AT gmail.com SoftLeader Tech. Corp. Taiwan Java Annotation Lesson 1.
OpenAccess ORM Advanced Topics Kevin Babcock April 9, 2009.
CS6320 – Java Persistence API
Chengyu Sun California State University, Los Angeles
Java Persistence Architecture (JPA)
Java Persistence: Object Inheritance Mapping
Advanced Java Programming
Hibernate (JPA) Code First Entity Relations
Translation of ER-diagram into Relational Schema
Java Data Persistence Using Hibernate
By Rajanikanth B OOP Concepts By Rajanikanth B
CS4961 Software Design Laboratory Understand Aquila Backend
Topics Persistence API for JAVA EE5 Java Transaction API Entity class.
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Introduction to Entities

Object-Relational Mapping You can perform queries on each field! is NOT serialization! You can perform queries on each field!

The Sun Java Data Objects (JDO) specification, defines portable APIs to a persistence layer that is conceptually neutral to the database technology used to support it. It can thus be implemented by vendors of relational and object-oriented databases. The new Java Persistence specification finally defines a standardized object-relational mapping and requires compliant products to implement it. There is now a broad industry consensus on a portable programming model for persistent Java objects.

Entities Entities have a client-visible, persistent identity (the primary key) that is distinct from their object reference. Entities have persistent, client-visible state. Entities are not remotely accessible. An entity’s lifetime may be completely independent of an application’s lifetime. Entities can be used in both Java EE and J2SE environments

Entities - example This demo entity represents a Bank Account. The entity is not a remote object and can only be accessed locally by clients. However, it is made serializable so that instances can be passed by value to remote clients for local inspection. Access to persistent state is by direct field access. package examples.entity.intro; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Account implements Serializable { // The account number is the primary key @Id public int accountNumber; public int balance; private String ownerName; String getOwnerName() {return ownerName;} void setOwnerName(String s) {ownerName=s;} /** Entities must have a public no-arg constructor */ public Account() { // our own simple primary key generation accountNumber = (int) System.nanoTime(); }

Entities - example public void deposit(int amount) { balance += amount; } public int withdraw(int amount) { if (amount > balance) { return 0; } else { balance -= amount; return amount; The entity can expose business methods, such as a method to decrease a bank account balance, to manipulate or access that data. Like a session bean class, an entity class can also declare some standard callback methods or a callback listener class. The persistence provider will call these methods appropriately to manage the entity.

Access to the entity’s persistent state is by direct field access Access to the entity’s persistent state is by direct field access. An entity’s state can also be accessed using JavaBean-style set and get methods. The persistence provider can determine which access style is used by looking at how annotations are applied. In Source 6.1, the @Id annotation is applied to a field, so we have field access.

Access to the Entity package examples.entity.intro; import java.util.List; import javax.ejb.Stateless; import javax.ejb.Remote; import javax.persistence.PersistenceContext; import javax.persistence.EntityManager; import javax.persistence.Query; @Stateless @Remote(Bank.class) public class BankBean implements Bank { @PersistenceContext private EntityManager manager; public List<Account> listAccounts() { Query query = manager.createQuery ("SELECT a FROM Account a"); return query.getResultList(); } public Account openAccount(String ownerName) { Account account = new Account(); account.ownerName = ownerName; manager.persist(account); return account;

Access to the Entity public int getBalance(int accountNumber) { Account account = manager.find(Account.class, accountNumber); return account.balance; } public void deposit(int accountNumber, int amount) { account.deposit(amount); public int withdraw(int accountNumber, int amount) { return account.withdraw(amount); public void close(int accountNumber) { manager.remove(account);

Persistence.xml <?xml version=”1.0” encoding=”UTF-8”?> <persistence xmlns=”http://java.sun.com/xml/ns/persistence”> <persistence-unit name=”intro”/> </persistence> A persistence unit is defined in a special descriptor file, the persistence.xml file, which is simply added to the META-INF directory of an arbitrary archive, such as an Ejb-jar, .ear, or .war file, or in a plain .jar file.

Advanced Persistency Inheritance

Mapping inheritance

SINGLE TABLE PER CLASS etc. Id numPass numWheels make model 1 6 2 HORSECART NULL Id numPass numWheels make model acceleratorType 2 1 HONDA HRC7 THROTTLE etc. Problems with polymorphism – how do you find “all RoadVehicles that have less than 3 passenger?”

SINGLE TABLE PER CLASS HIERARCHY Id numPass numWheels make model DISC acceleratortype BoringFactor CoolFactor 1 6 2 HORSECART NULL ROADVEHICLE HONDA HRC7 MOTORCYCLE THROTTLE 3 4 FIAT PUNTO CAR PEDAL FERRARI F70 COUPE 5 FORD KA ROADSTER Space inefficiency Impossible to set “NON-NULL” constraints on fields of the subclasses.

JOINED TABLES RoadVehicle Car Coupe Id DTYPE numPass numWheels make model 1 ROADVEHICLE 6 2 HORSECART NULL MOTORCYCLE HONDA HRC7 3 CAR 4 FIAT PUNTO COUPE FERRARI F70 5 ROADSTER FORD KA Car Coupe Id acceleratortype 3 PEDAL 4 5 Id boringFactor 4 1 Many joins in a deep inheritance hierarchy – time inefficiency.

The base class package examples.entity.single_table; // imports go here @Entity(name=”RoadVehicleSingle”) @Table(name=”ROADVEHICLE”) //optional, it’s the default @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name=”DISC”, discriminatorType=DiscriminatorType.STRING) @DiscriminatorValue(“ROADVEHICLE”) // @Inheritance(strategy=InheritanceType.JOINED) public class RoadVehicle implements Serializable { public enum AcceleratorType {PEDAL,THROTTLE}; @Id protected int id; protected int numPassengers; protected int numWheels; protected String make; protected String model; public RoadVehicle() { id = (int) System.nanoTime(); } // setters and getters go here ...

The derived class package examples.entity.single_table; // imports go here @Entity @DiscriminatorValue(“MOTORCYCLE”) //not needed for joined public class Motorcycle extends RoadVehicle implements Serializable { public final AcceleratorType acceleratorType =AcceleratorType.THROTTLE; public Motorcycle() { super(); numWheels = 2; numPassengers = 2; }

Advanced Persistency Relationships

Multiplicity and Directionality – 7 types Unidirectional Bidirectional 1:1 1:N N:1 N:M

Watch out for side effects! Let r be a 1:N relationship Let rel be a 1:1 relationship a one rel Before a one two r b two b three four a.setRel(two) a.setR(three) rel After a one a one two b two r b three four

Cascade-delete Order Shipment a one When we delete “a”, should also one,two e three be canceled? two three

Relation – 1:1 unidir – “from” @Entity(name=”OrderUni”) public class Order implements Serializable { private int id; private String orderName; private Shipment shipment; public Order() { id = (int)System.nanoTime(); } @Id public int getId() { return id; } public void setId(int id) { this.id = id; } ... // other setters and getters go here @OneToOne(cascade={CascadeType.PERSIST}) public Shipment getShipment() { return shipment; public void setShipment(Shipment shipment) { this.shipment = shipment;

Relation – 1:1 unidir – “to” ... @Entity(name=”ShipmentUni”) public class Shipment implements Serializable { private int id; private String city; private String zipcode; public Shipment() { id = (int)System.nanoTime(); } @Id public int getId() { return id; } public void setId(int id) { this.id = id; } // other setters and getters go here }

Relation – 1:1 unidir – client ... @Stateless public class OrderShipmentUniBean implements OrderShipment { @PersistenceContext EntityManager em; public void doSomeStuff() { Shipment s = new Shipment(); s.setCity(“Austin”); s.setZipcode(“78727”); Order o = new Order(); o.setOrderName(“Software Order”); o.setShipment(s); em.persist(o); } public List getOrders() { Query q = em.createQuery(“SELECT o FROM OrderUni o”); return q.getResultList();

Relation – 1:1 bidir – “to” ... @Entity(name=”ShipmentUni”) public class Shipment implements Serializable { private int id; private String city; private String zipcode; private Order order; public Shipment() { id = (int)System.nanoTime(); } @Id public int getId() { return id; } public void setId(int id) { this.id = id; } // other setters and getters go here @OneToOne(mappedBy=”shipment”) // shipmentproperty from the Order entity public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order;

Relation – 1:1 bidir – client ... @Stateless public class OrderShipmentUniBean implements OrderShipment { @PersistenceContext EntityManager em; public void doSomeStuff() { Shipment s = new Shipment(); s.setCity(“Austin”); s.setZipcode(“78727”); Order o = new Order(); o.setOrderName(“Software Order”); o.setShipment(s); em.persist(o); } public List getOrders() { Query q = em.createQuery(“SELECT o FROM OrderUni o”); return q.getResultList(); .. public List getShipments() { Query q = em.createQuery(“SELECT s FROM Shipment s”);

Relation – 1:N unidir – “from” ... @Entity(name=”CompanyOMUni”) public class Company implements Serializable { private int id; private String name; private Collection<Employee> employees; // other getters and setters go here // including the Id @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.EAGER) public Collection<Employee> getEmployees() { return employees; } public void setEmployees(Collection<Employee> employees) { this.employees = employees;

Relation – 1:N unidir – “to” ... @Entity(name=”EmployeeOMUni”) public class Employee implements Serializable { private int id; private String name; private char sex; // other getters and setters go here // including the Id }

Relation – 1:N unidir – client Company c = new Company(); c.setName(“M*Power Internet Services, Inc.”);Collection<Employee> employees = new ArrayList<Employee>(); Employee e = new Employee(); e.setName(“Micah Silverman”); e.setSex(‘M’); employees.add(e); e = new Employee(); e.setName(“Tes Silverman”); e.setSex(‘F’); employees.add(e); c.setEmployees(employees); em.persist(c); c = new Company(); c.setName(“Sun Microsystems”); employees = new ArrayList<Employee>(); e.setName(“Rima Patel”); e.setSex(‘F’); employees.add(e); e.setName(“James Gosling”); e.setSex(‘M’); employees.add(e);

Relation – 1:N bidir – “from” ... @Entity(name=”CompanyOMUni”) public class Company implements Serializable { private int id; private String name; private Collection<Employee> employees; // other getters and setters go here // including the Id @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.EAGER, mappedBy=”company”) public Collection<Employee> getEmployees() { return employees; } public void setEmployees(Collection<Employee> employees) { this.employees = employees;

Relation – 1:N bidir – “to” ... @Entity(name=”EmployeeOMUni”) public class Employee implements Serializable { private int id; private String name; private char sex; private Company company; // other getters and setters go here // including the Id @ManyToOne public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company;

Relation – M:N The rules for generating a join table are: 1. The name of the join table will be the name of the owning entity, followed by an underscore (_), followed by the name of the target entity. 2. The name of the first column in the join table will be the property name, followed by an underscore, followed by the primary key name in the owner entity. 3. The name of the second column in the join table will be the property name, followed by an underscore, followed by the primary key name in the target entity. 4. The types of the columns in the join table will match the primary key types of the tables that will be referenced by it.

Relation – M:N unidir – “from” ... @Entity(name=”StudentUni”) public class Student implements Serializable { private int id; private String name; private Collection<Course> courses = new ArrayList<Course>(); public Student() { id = (int)System.nanoTime(); } @Id public int getId() { return id; } //other setters and getters go here @ManyToMany(cascade={CascadeType.ALL},fetch=FetchType.EAGER) @JoinTable(name=”STUDENTUNI_COURSEUNI”) public Collection<Course> getCourses() { return courses; } public void setCourses(Collection<Course> courses) { this.courses = courses;

Relation – M:N unidir – “to” ... @Entity(name=”CourseUni”) public class Course implements Serializable { private int id; private String courseName; private Collection<Student> students = new ArrayList<Student>(); //setters and getters go here }

Relation – M:N bidir – “from” ... @Entity(name=”StudentUni”) public class Student implements Serializable { private int id; private String name; private Collection<Course> courses = new ArrayList<Course>(); public Student() { id = (int)System.nanoTime(); } @Id public int getId() { return id; } //other setters and getters go here @ManyToMany(cascade={CascadeType.ALL},fetch=FetchType.EAGER) @JoinTable(name=”STUDENTUNI_COURSEUNI”) public Collection<Course> getCourses() { return courses; } public void setCourses(Collection<Course> courses) { this.courses = courses;

Relation – M:N bidir – “to” ... @Entity(name=”CourseBid”) public class Course implements Serializable { private int id; private String courseName; private Collection<Student> students = new ArrayList<Student>(); //getters and setters go here @ManyToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER,mappedBy=”courses”) public Collection<Student> getStudents() { return students; } public void setStudents(Collection<Student> students) { this.students = students;