• Like

Loading…

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Slides persistence tier using oracle and jpa ed111_03

  • 3,138 views
Uploaded on

 

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
3,138
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
356
Comments
0
Likes
2

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Persistence Tier using Oracle and JPA-Day 3 ER/CORP/CRS/ED111/003 Ver. No.: 1.0 Copyright © 2008, Infosys Technologies Ltd. Education and Research We enable you to leverage knowledge anytime, anywhere! Confidential
  • 2. General Guideline
    • © (2008) Infosys Technologies Ltd.
    • This document contains valuable confidential and proprietary information of Infosys. Such confidential and proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and commercialized. Such information is furnished herein for training purposes only. Except with the express prior written permission of Infosys, this document and the information contained herein may not be published, disclosed, or used for any other purpose.
  • 3. Confidential Information
    • This Document is confidential to Infosys Technologies Limited. This document contains information and data that Infosys considers confidential and proprietary (“Confidential Information”).
    • Confidential Information includes, but is not limited to, the following:
      • Corporate and Infrastructure information about Infosys
      • Infosys’ project management and quality processes
      • Project experiences provided included as illustrative case studies
    • Any disclosure of Confidential Information to, or use of it by a third party, will be damaging to Infosys.
    • Ownership of all Infosys Confidential Information, no matter in what media it resides, remains with Infosys.
    • Confidential information in this document shall not be disclosed, duplicated or used – in whole or in part – for any purpose other than reading without specific written permission of an authorized representative of Infosys.
    • This document also contains third party confidential and proprietary information. Such third party information has been included by Infosys after receiving due written permissions and authorizations from the party/ies. Such third party confidential and proprietary information shall not be disclosed, duplicated or used – in whole or in part – for any purpose other than reading without specific written permission of an authorized representative of Infosys.
  • 4. Recap
    • Triggers
    • Packages
    • Data Transfer Utilities
  • 5. Session Plan
      • JDBC
      • Introduction to Java Persistence API (JPA)
  • 6. Persistence Tier (JDBC/JPA)
  • 7. JDBC ER/CORP/CRS/ED111/003 Ver. No.: 1.0 Copyright © 2008, Infosys Technologies Ltd. Education and Research We enable you to leverage knowledge anytime, anywhere! Confidential
  • 8. JDBC
    • The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way
    • JDBC is a specification that
      • tells the database vendors how to write a driver program to interface Java programs with their database
      • tells the programmers how to write a Java program to access any database
    • A Driver written according to this standard is called the JDBC Driver
    • All related classes and interfaces are present in the java.sql package
    • All JDBC Drivers implement the interfaces of java.sql
  • 9. JDBC Architecture and Drivers
    • Four types of drivers
      • Type 1 Driver or JDBC-ODBC Bridge Driver
      • Type 2 Driver or Native-API Driver
      • Type 3 Driver or Network-Protocol Driver
      • Type 4 Driver or Native-Protocol Driver
  • 10. Comparison Between Drivers   Also known as Conversion style Is it pure java Dependencies Type 1 JDBC-ODBC Bridge JDBC method calls into ODBC function calls No Yes Type 2 Native-API driver JDBC method calls into native calls of the database API No Yes Type 3 Network-Protocol Driver Middle-tier (application server) converts JDBC calls directly or indirectly into the vendor-specific database protocol Yes No Type 4 Native-Protocol Driver JDBC calls directly into the vendor-specific database protocol Yes No
  • 11. Database Interaction in JDBC
    • The steps involved in a database interaction are:
      • Loading the specific driver
      • Making a connection to the database
      • Sending SQL statements to the database
      • Processing the results
  • 12. Loading the Database Driver
    • We load the driver class by calling Class.forName() with the Driver class name as an argument.
    • Once loaded, the Driver class creates an instance of itself.
    • The General format is :
    • Class.forName( String ClassName );
    • Class is a class in java.lang package.
    • Example : Class.forName("oracle.jdbc.driver.OracleDriver");
  • 13. DriverManager class
      • Manages all the JDBC Drivers that are loaded in the memory
      • Helps in dynamic loading of Drivers
      • Its getConnection() method is used to establish a connection to a database.
      • It uses a username, password, and a jdbc url to establish a connection to the database and returns a connection object.
  • 14. Connection interface
    • Defines methods for interacting with the database via the established connection.
      • A connection object represents a connection with a database.
      • A connection session includes the SQL statements that are executed and the results that are returned over that connection.
      • A single application can have one or more connections with a single database, or it can have many connections with many different databases .
      • Example :
      • Connection connection = DriverManager. getConnection (
      • "jdbc:oracle:thin: @10.122.130.31:1521:training",“scott", “tiger");
  • 15. Creating a Statement object
    • Once a connection is obtained we can interact with the database.
    • Connection interface defines methods for interacting with the database via the established connection.
    • To execute SQL statements, we need to instantiate a Statement object from the connection object by using the createStatement() method.
    • Statement statement = connection .createStatement();
    • A statement object is used to send and execute SQL statements to a database. 
  • 16. Statement interface
    • Defines methods that are used to interact with database via the execution of SQL statements.
    • The different methods are:
      • executeQuery(String sql) - executes an SQL statement (SELECT) that queries a database and returns a ResultSet object.
      • executeUpdate(String sql) - executes an SQL statement (INSERT,UPDATE,or DELETE) that updates the database and returns an int, the row count associated with the SQL statement
  • 17. ResultSet Interface
    • Maintains a pointer to a row within the tabular results.
    • The next() method is used to successively step through the rows of the tabular results. It is initialized to a position before the first row. We must call next() once to move it to the first row.
    • The different methods are:
      • getBoolean(int) - Get the value of a column in the current row as a Java boolean.
      • getByte(int) - Get the value of a column in the current row as a Java byte.
      • getDouble(int) - Get the value of a column in the current row as a Java double.
      • getInt(int) - Get the value of a column in the current row as a Java int.
  • 18. Using Statement and ResultSet
  • 19. Creating a PreparedStatement object
    • Helps us to work with precompiled SQL statements
    • Precompiled SQL statements are faster than normal statements
    • So, if a SQL statement is to be repeated, it is better to use PreparedStatement
    • To execute SQL statements, we need to instantiate a PreparedStatement object from the connection object by using the prepareStatement () method.
    • PreparedStatement preparedStatement = connection. prepareStatement ("select * from student where sid=?");
    • Some values of the statement can be represented by a ? character which can be replaced later using setXXX () method
  • 20. PreparedStatement Demo
  • 21. Demos (Self Study)
  • 22. ResultSetMetaData Interface
    • Holds information on the types and properties of the columns in a ResultSet .
    • Provides information about the database as a whole. Constructed from the Connection object
    • Some of the methods are:
      • String getColumnName(int column)
      • String getColumnTypeName(int column)
      • int getColumnCount();
  • 23. Transaction Management using JDBC
    • By default, auto commit mode of the connection reference is set to true
    • A transaction can be done as follows using methods of the Connection interface
    ... connection. setAutoCommit (false); //by default it is true try{ //Statements connection. commit (); } catch(Exception exception){ connection. rollback (); }
  • 24. Can you answer the following ?
      • Why JDBC ?
      • How to Set up a connection to a database from Java using JDBC?
      • What are the different methods provided by statement interface?
      • Why do you prefer preparedstatement over statement interface ?
  • 25. Summary
    • Java Data Base Connectivity
      • JDBC API
      • Different drivers
      • Set up a connection to a database from Java
      • Create a database application
  • 26. Introduction to JPA ER/CORP/CRS/ED111/003 Ver. No.: 1.0 Copyright © 2008, Infosys Technologies Ltd. Education and Research We enable you to leverage knowledge anytime, anywhere! Confidential
  • 27. Data Persistence
    • Data persistence is one of the most critical operations for Enterprise Applications.
    • Persistent data normally refers to permanent data in an application.
    • The state of these data is made permanent by storing them in a persistent medium like database, files or a disk tape.
  • 28. Java Persistence API (JPA)
    • JPA provides
      • API for persistence
      • Object/Relational(O/R) metadata(Annotation)
      • Java Persistence Query Language(JPQL)
    • Persistence deals with storing and retrieving of application data
    • It is done with the help of Entity(Java Object)
  • 29. ORM Example Customer - customerID - int - name - String Customer customerID:int(8) Name:varchar2(20) Employee - EmployeeId-int - Name-String Employee EmployeeID:int(8) Name:varchar2(10) Account - AccountId- int Saving Account Current Account Account AccountID:int(8) ……… Account -TransactionID - int
    • AccountId- int
    • Type -String
    Transaction TransactionID : int(8 ……… . * Transaction
  • 30. Entity
    • An Entity refers to a logical collection of data that can be stored or retrieved as a whole. Entity is a java object.
    • For example, in a banking application, Account can be an Entity.
    • accountNumber, balance etc are properties/attributes of Account Entity.
    • Identity property is used to identify one unique entity among multiple entities (or multiple entity instances) in a database. In Account Entity accountNumber acts as an Identity property.
  • 31. Creating an Entity
    • A persistable class must be annotated or prefixed with javax.persistence.Entity annotation.
    • The instance of the class will represent one row in the table.
    • By default, the table name corresponds to the class name.
    • Each property should have getter and setter method.
    • The class should contain default or no-argument constructor
  • 32. Employee Bean public class Employee { private int empId; private String name; public Employee() {} public Employee(int empId) { this. empId = empId; } public int getEmpId() { return empId; } public void setEmpId(int empId) { this. empId = empId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
  • 33. Employee Entity @Entity // To make Employee as an Entity public class Employee { @Id // To make empId as primary key private int empId; private String name; public Employee() {} public Employee(int empId) { this. empId = empId; } public int getEmpId() { return empId; } public void setEmpId(int empId) { this. empId = empId; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Employee Table empId(PK) name 101 John 102 Jack 103 Joe
  • 34. Mapping to a Table
    • @Entity and @Id annotations need to be specified to map an entity to a database table.
    • By default, table name will be the name of the entity class without the package name.
    • @Table annotation will be used to specify the name of the table if the names are different.
    • Overriding the default table name
      • @Entity
      • @Table(name="EMP")
      • public class Employee { ... }
    EMP Table empId(PK) name 101 John 102 Jack 103 Joe
  • 35. Column Mappings Employee Table
        • @Entity
        • public class Employee {
        • @Id
        • @Column (name=" EMP_ID ")
        • private int id;
        • @Column (name=“ EMP_NAME ")
        • private String name;
        • // ...getter and setter methods
        • }
    • @Column annotation will be used to specify the name of the column
    • if entity property name is different from column name in the table
    EMP_ID EMP_NAME 101 John 102 Jack 103 Joe
  • 36. Temporal Types
    • Temporal types are the set of time-based types
    • To persist Temporal data types of java, @Temporal annotation is used
    • The list of supported temporal types used in Entity
        • java.util.Date and java.util.Calendar
  • 37. Mapping Temporal Types Different Temporal Types from JPA @Entity public class Employee { @Id private int id; @Temporal (TemporalType.DATE) private Calendar dob; @Temporal (TemporalType.TIME) private Date startDate; // ... } In Entity Mapped To Database TemporalType. DATE Mapped to java.sql.Date TemporalType. TIME Mapped to java.sql.Time TemporalType. TIMESTAMP Mapped to java.sql.Timestamp
  • 38. Transient State
    • Attributes that are part of an entity but not required to be persisted should be prefixed with the @Transient annotation
    @Entity public class Employee { @Id private int empid; private String name; private long salary; @Transient private String translatedName ; // getter and setter method } Employee Table translatedName will not be persisted empid name salary 100 John 1000 101 Jack 2000
  • 39. Persisting an Entity Using JPA
    • Steps involved in persisting an Entity are
      • Configuring persistence unit in persistence.xml
      • Creating an instance of EntityManagerFactory
      • Obtaining instance of EntityManager
      • Persist the Entity
        • Begin EntityTransaction
        • Invoke persist() method
        • Commit the Transaction
      • Next
  • 40. EntityManagerFactory
    • It is used to create an instance of EntityManager
    • EntityManagerFactory emf = Persistence.
    • createEntityManagerFactory("EmployeeService");
    • Obtaining an EntityManager from an EntityManagerFactory
    • reference
    • EntityManager em = emf.createEntityManager();
    • Back
    Persistent Unit name.
  • 41. EntityManager
    • Provides API for interacting with the Entity
    • Some of the functions provided by EntityManager API are:
      • persist() – save a new entity to the database table
      • remove() –remove the entity from the database table
      • find() – Get the existing entity from the database table
      • Back
  • 42. Persistence Unit
    • A persistent unit is a collection of entities that are managed together.
    • It specifies the persistent provider name, entity class names, and properties like the database connection URL, driver, user and password etc.
    • Persistence Unit is defined inside persistence.xml file.
    • Each persistence unit has a name.
    • EntityManagerFactory needs the name of the persistence unit to persist an entity
    • Back
  • 43. persistence.xml
    • <?xml version= &quot;1.0&quot; encoding=&quot;UTF-8&quot;?>
    • <persistence version= &quot;1.0&quot; xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd&quot;>
    • < persistence-unit name= &quot; EmployeeService &quot; transaction-type=&quot;RESOURCE_LOCAL&quot;>
    • <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
    • <class>com.infy.Employee</class>
    • <properties>
    • <property name= &quot;toplink.jdbc.url&quot; value=“ jdbc:oracle:thin: @10.122.130.40:1521/georli01&quot;/>
    • <property name= &quot;toplink.jdbc.user&quot; value=&quot;er106657&quot;/>
    • <property name= &quot;toplink.jdbc.driver&quot; value=&quot;oracle.jdbc.driver.OracleDriver&quot;/>
    • <property name= &quot;toplink.jdbc.password&quot; value=&quot;infy&quot;/>
    • <property name= &quot;toplink.ddl-generation&quot; value=&quot;create-tables&quot;/>
    • </properties>
    • </persistence-unit>
    • </persistence> Click here to know more on Persistence Unit
  • 44. Persisting an Entity (1 of 2)
    • Persisting an entity is saving its state so that it can be retrieved later.
    • EntityManagerFactory emf = Persistence. createEntityManagerFactory(&quot;EmployeeService&quot;);
    • EntityManager em = emf.createEntityManager();
    • EntityTransaction et=em.getTransaction();
    • et.begin();
    • Employee employee = new Employee();
    • employee.setEmpId(158);
    • employee.setName(“Ritchie”);
    • em.persist(employee);
    • if(et!=null) {
    • et.commit();}
    • Entities must be persisted using a Transaction.
  • 45. Persisting an Entity (2 of 2)
    • <persistence-unit name=&quot; EmployeeService &quot; transaction-type=&quot;RESOURCE_LOCAL&quot;>
    • <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
    • <class> </class>
    • <properties>
    • <property name=&quot;toplink.jdbc.url . . . .
    • . . . . . . .value=&quot;create-tables&quot;/>
    • </properties>
    • </persistence-unit>
    package com.infy @Entity public class Employee { @Id int empId; String name; //getter and setter } EntityManagerFactory emf = Persistence.createEntityManagerFactory(“ &quot;); EntityManager em = emf.createEntityManager(); EntityTransaction et=em.getTransaction(); et.begin(); Employee emp1= new Employee(); emp1.setEmpID(158); emp1.setName(“Ritchie”); em.persist(emp1); et.commit(); EmployeeService com.infy .Employee EMPID NAME 158 Ritchie
  • 46. Finding an Entity
    • An entity can be retrieved using the EntityManager
    • Employee employee = em.find(Employee.class, 158);
    • The first argument is Entity class
    • The second argument is the id or primary key that identifies the particular entity
    • If that record does not exist in the table, find() returns null.
  • 47. Updating an Entity
    • In order to update an entity, the entity must be present in the persistence context.
    • EntityTransaction et=em.getTransaction();
    • et.begin();
        • Employee emp = em.find(Employee.class, 158);
        • if (emp != null) {
        • emp.setSalary(emp.getSalary() + 1000);
        • }
        • et.commit();
  • 48. Removing an Entity
    • Similar to DELETE operation in the database
    • In order to remove an entity, the entity must be present in the persistence context
    • A simple example for removing a row from employee table is:
    • EntityTransaction et=em.getTransaction();
    • et.begin();
        • Employee emp = em.find(Employee.class, 158);
        • if (emp != null) {
        • em.remove(emp);
        • }
        • et.commit();
  • 49. Demos
  • 50. Entity Life Cycle Does not exist new removed managed detached Object Construction Object obj=new Object();
    • EntityManager.remove(obj)
    • @PreRemove
    • Pending removal in database
    • EntityManager.persist (obj)
    • @PrePersist
    • Database insert
    • @PostPersist
    Transaction Ends
    • Update Query
    • @Pre Update
    • Database Update
    • @Post Update
  • 51. Life cycle callback Methods
    • Callback methods are called automatically by the application when a particular condition is met.
    • It is often necessary to perform various actions at different stages of a persistent object's lifecycle.
    • JPA includes a variety of callback methods.
    • These methods will be called automatically by the application for life cycle events of an entity
    • They can be defined on the persistent classes themselves or on non-persistent listener classes.
  • 52. Annotations for call back methods
    • Call back methods should be prefixed by any one of the following annotation
    Annotation Description @PrePersist Invoked for an entity before persist operation is executed. @PostPersist Invoked for an entity after persist operation is executed @PreRemove Invoked for an entity before remove operation is executed @PostRemove Invoked for an entity after remove operation is executed. @PreUpdate Invoked for an entity before update operation is executed @PostUpdate Invoked for an entity after update operation is executed
  • 53. Call back methods inside Entity
    • Any method may be used which takes no arguments
    • Multiple annotation can be assigned to a single method.
    • Same life cycle annotation cannot be given to many methods
  • 54. Example @Entity public class Employee { @Id private int empId; .... public Employee() {} public int getEmpId(){ return empId; } public void setEmpId(int empId){ this. empId = empId; } .... @PrePersist public void initialize() { System.out.println(&quot;Trying to insert&quot;); } } The initialize method will be called automatically before persisting the Entity. The method name may be anything but it should be prefixed with @PrePersist
  • 55. Using Entity Listeners
    • Mixing lifecycle event code into persistent classes is not a good practice.
    • It is better to handle lifecycle events in a non-persistent listener class (a simple java class).
    • Listener classes must have a public no-argument constructor
    • Listener classes can implement any number of callbacks
    • The callback methods must take single argument of type java.lang.Object or Entity
  • 56. Example Entity @Entity @EntityListeners( EmployeeListener.class) public class Employee { @Id private int id; .... .... public Employee() {} public int getId() {return id;} public void setId(int id) { this.id = id; } .... } Listener public class EmployeeListener { @PrePersist public void initialize(Employee e) { System.out.println(&quot;Trying to insert&quot;); } }
  • 57. Can you answer these questions?
    • What are the following annotations used for
      • @Id @Table
      • @Transient @Temporal
    • What are the steps involved in persisting an Entity?
    • What are the different attributes of Persistence Unit?
    • What are the various ways of implementing lifecycle callback methods?
  • 58. Thank You “ The contents of this document are proprietary and confidential to Infosys Technologies Ltd. and may not be disclosed in whole or in part at any time, to any third party without the prior written consent of Infosys Technologies Ltd.” “ © 2008 Infosys Technologies Ltd. All rights reserved. Copyright in the whole and any part of this document belongs to Infosys Technologies Ltd. This work may not be used, sold, transferred, adapted, abridged, copied or reproduced in whole or in part, in any manner or form, or in any media, without the prior written consent of Infosys Technologies Ltd.”
  • 59. Appendix ER/CORP/CRS/ED111/003 Ver. No.: 1.0 Copyright © 2008, Infosys Technologies Ltd. Education and Research We enable you to leverage knowledge anytime, anywhere! Confidential
  • 60. CallableStatement (1 of 3)
    • Helps us to call stored procedures and functions
    • To call a procedure/function, we need to instantiate a CallableStatement object from the connection object by using the prepare Call () method.
    • CallableStatement callableStatement = connection.
    • prepareCall (&quot;{call GetSalary(?,?)}&quot;);
    • Some values of the statement can be represented by a ? character which can be replaced later using setXXX () method. This is used for input (in) parameters
  • 61. CallableStatement (2 of 3)
    • The out parameters are to be registered
      • callableStatement. registerOutParameter (int parameterIndex, int SQLType);
    • To get the value stored in the out parameter--
      • callableStatement. getXXX (int parameterIndex);
  • 62. CallableStatement (3 of 3)