• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content

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.

Like this presentation? Why not share!

Slides persistence tier using oracle and jpa ed111_05

on

  • 2,195 views

 

Statistics

Views

Total Views
2,195
Views on SlideShare
2,195
Embed Views
0

Actions

Likes
2
Downloads
290
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • JPA contains a new query language called JPQL. It is very similar to SQL that is used with JDBC. The basic difference between both these query language is SQL operates on tables and columns whereas JPQL operates on objects and attributes which makes it independent of database you use as the queries are on Entities. All the JPQL queries are translated to SQL queries by the JPQL processor.
  • SQL with JDBC uses SQL queries whereas JPQL using its own queries known as JPQL queries. The SQL queries in JDBC operates on tables and columns whereas JPQL queries operates on objects and attributes. All the operations(select, update, delete, insert) are possible in JDBC but JPQL does not support an insert operation because JPA provides you with persist method for insertion. Using JDBC the programmer has to take care of opening and closing the connection where as in JPQL there is no direct connection of the java class with the database you use. JDBC is basically used for small applications , because if the application has large amount of data to be stored or update , More lines of code need to be written in JDBC , as we have to externally deal with the bean class and the database, whereas in JPA dealing with Entity reflects dealing with D/B as the entity and database are internally mapped.
  • For getting the EntityManager reference, refer to Day 3 slides
  • The Query Interface is similar to JDBC Statement interface.
  • The Query interface is used for defining and executing queries
  • This example shows the mapping of an Entity class with the table in database. The table has four columns as candidateId, name, marks, DOB whereas the Entity class also has the same attributes declared as private members of the class
  • Using the reference of the EntityManager , you can create queries with createQuery(“select k from Candidate k”) method. If you see this query it is very similar to an SQL query. This can be compared with the Statement interface of JDBC API. The same query in JDBC will be written as “select * from candidate” where candidate is the name of Table in the database. And in JPQL it is written as “select k from Candidate k” where Candidate is the name of the Entity class(@Entity) and k is the reference of the Entity class.
  • When a query returns multiple instances of an entity then getResultList() is to be used. If it returns only once instance of an entity then getSingleResult() can be used. getSingleResult() will throw run time exceptions if there are no rows are selected from the table or if more than one row is selected. get(int) method returns only Object type. This have to be type casted to the required class type. The following code illustrates this: Candidate cd=(Candidate)rs.get(i);
  • The two techniques for setting parameters are Named and Positional
  • This is one of the techniques for setting the parameters of a query. This technique is called Naming Parameter technique. When setting the parameter colon(:) will be used. And setParameter() is the method used to set a parameter. The name that is given to the parameter in the query after :(colon) sign will be the name that will be used in setParameter() to set the value. Here cId and cid represents the name and value respectively.
  • This is the second technique to specify a parameter in JPQL. This is very much similar to PreparedStatement in JDBC. In Prepared Statement we use only ? And here with ? we have to specify the position of a particular parameter. This numeric 1 here represents the position number for this parameter. The ?1 in the above query represents that k.candidateid is the first parameter. ? Represents that this is the parameter for which the value will be set and numeric 1 represents the position of this parameter. In JDBC we only mention the ? and automatically positions are assigned to the parameters in order in which they appear.
  • If the same update statement is written using Positional parameter technique then the query looks like Query query=em.createQuery("update Candidate cd set cd.DOB=?1 where cd.candidateid=?2); query.setParameter(1, dateOfBirth ); query.setParameter(2, cid); int update=query.executeUpdate();
  • The named queries are defined with the @ NamedQuery annotation. The basic purpose of defining a NamedQuery is reusability. These queries are stored and can be reused across applications. The name attribute of the @NamedQuery annotation represents the name of the query. It is always a good practice to name a query in relation to the output it produces. createNamedQuery() method will be used to create a named query of the same name defined in @NamedQuery
  • If more than one query have to be defined for a single entity then @NamedQueries should be used.
  • createNativeQuery method of EntityManger class will be used to invoke a stored function. ?1 in the SQL expression represents the first IN parameter of the stored function. The setParameter method will be used to set the value of the parameter. getSingleResultList() method will be used to get the return value of the stored function. Check The method getSingleResult return you an object of Vector type, so we explicitly typecast it to (List). And as List is raw type of collection which is iterated index based , we get the elements of List by using .get(i) where I represents the index position. We can use vector kind of object also , but it is a sychronized which makes it less efficient.
  • There is always a need of expression and operators whenever some complex queries have to be written. The usage of expressions and operators in JPQL are very similar to SQL in JDBC. JPQL can also include sub queries.
  • Where clause is used to apply the join condition. From clause will contain the entities to create a join relationship If different types of entities are retrieved, then the List will contain array of Objects ,with each object representing the select clause elements, as its array elements. In the object array , the first element will refer to first selected element , the second to the second and so on. By typecasting to Object, elements can be retrieved.
  • createNativeQuery method of EntityManger class will be used to call a Procedure. The setParameter method will be used to set the value of the parameter. executeUpdate() method will be used to execute the procedure.

Slides persistence tier using oracle and jpa ed111_05 Slides persistence tier using oracle and jpa ed111_05 Presentation Transcript

  • Persistence Tier using Oracle and JPA-Day 5 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
  • 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.
  • 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.
  • Recap
    • Primary Key Generation Methods
    • Inheritance
    • Entity Relationships
  • Session Plan
    • Introduction to JPQL
    • JDBC VS JPQL
    • The Query API
    • CRUD in JPQL
    • Queries in JPQL
    • Join Operations in JPQL
    • Calling Stored Functions using JPQL
  • JPQL 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
  • What is JPQL and where it is being used?
    • JPQL stands for Java Persistence Query Language. This query language is provided by JPA to deal with Entities
    • This technology is used in building enterprise applications
  • JPQL(Java Persistence Query Language)
    • JPA provides a Query Language called JPQL
    • Queries on Entities(Not on tables and columns)
    • Easy to adapt as syntax is similar to SQL
    • Operates on Objects and Relationships
    • All JPQL queries will be translated to SQL queries by JPQL Query Processor
  • SQL with JDBC VS JPQL JPQL Query SQL Query JPQL Query Processor SQL with JDBC JPQL SQL Queries JPQL Queries Operates on Tables And Columns Operates on Objects and Attributes Suitable for Small Applications Suitable for Large Applications Operations(Select, Insert, Update, Delete) Only Select ,Update, Delete
  • Steps to Interact with Database using JPQL
    • Get EntityManager reference
    • Write Query
    • Set the Parameters
    • Execute the Query (Select, Update, Delete)
    • Get the Result
  • Query API (1 of 2)
    • It allows the developers to write queries on entities and retrieve them
    • The methods from EntityManager and Query Interface are used to perform database operations
    • The Query API allows the developers to use JPQL
  • Query API (2 of 2)
    • The Query API
    • Query
    • getSingleResult()
    • setParameter()
    • getResultList()
    • executeUpdate()
    FOR CREATING QUERY INSTANCES FOR DEFINING AND EXECUTING THE QUERY EXPRESSION LANGUAGE The Query interface EntityManager J P Q L
  • Entity Mapped with Table
    • @Entity
    • @Table(name="candidate")
    • public class Candidate {
    • @Id
    • private int candidateId;
    • private String name;
    • private int marks;
    • private String DOB;
    • //setters and getters
    • }
    CANDIDATEID NAME MARKS DOB Candidate Table
  • 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 JPQL OPERATIONS R - Retrieve U - Update D - Delete
  • Creating Query Instance
    • EntityManager.createQuery();
    Entity Class Query query=em.createQuery("select k from Candidate k"); K is of Candidate type
  • Retrieving (R)-selecting Entities
    • getResultList() – to execute a query which is returning
    • multiple results
    • getSingleResult() – execute query returning single result
    EntityManagerFactory emf=Persistence.createEntityManagerFactory(“JPQL&quot;); EntityManager em=emf.createEntityManager(); EntityTransaction et=em.getTransaction(); et.begin(); Query query=em.createQuery(&quot;select k from Candidate k&quot;); List rs=query.getResultList(); int size=rs.size(); for(int i=0;i<size;i++){ Candidate cd=(Candidate)rs.get(i); System.out.println(&quot;Dob &quot; +cd.getDOB()); System.out.println(&quot;Marks &quot; +cd.getMarks()); } Getters of Entity class contains the list of Candidate objects
  • read(R)-selecting single Attribute
    • Select clause contains a single attribute and not a complete entity
    • The query returns a list of objects of the selected attribute type
    • In the following example, the query returns list of String objects
    Query query=em.createQuery(&quot;select k.name from Candidate k&quot;); List rs=query.getResultList(); int size=rs.size(); for(int i=0;i<size;i++) { String name =(String)rs.get(i); System.out.println(&quot;Name of the candidate is &quot; +name); }
  • read(R)-selecting Multiple Attributes(1/2)
    • To select multiple attributes using JPQL , Array and List is used
    • The selected attributes are stored in the array and the array is stored in the List. If two rows are fetched then two arrays will be created and stored in the List
    • Example using Array and List
    Object obj1[]=new Object[2];//Object array obj1[0]=new Integer(3);//Store individual elements obj1[1]=new Double(2.4); List list=new ArrayList();//creating ArrayList list.add(obj1);//storing object array into ArrayList Object obj2[]=(Object[]) list.get(0); //Getting the array from list Integer i1=(Integer)obj2[0]; Double d1= (Double)obj2[1];
  • read(R)-selecting Multiple Attributes(2/2)
    • Select clause contains multiple attributes and not a complete Entity. So the List will contain array of objects.
    • The reference k is of Candidate type but k.name is of String type and k.marks is of Integer type.
    Query query=em.createQuery(&quot;select k.name,k.marks from Candidate k&quot;); List rs=query.getResultList(); int size=rs.size(); for(int i=0;i<size;i++) { Object [] obj=(Object[])rs.get(i); String name =(String)obj[0]; int marks=(Integer)obj[1]; System.out.println(&quot;Name of the candidate is &quot; +name); System.out.println(&quot;Marks of the candidate are &quot; +marks); }
  • Setting Parameters
    • Can be done in two ways
      • Named Parameters
      • Positional Parameters
  • Named Parameters
    • Query parameters are prefixed with a colon(:)
    • To set the value of a parameter use the method setParameter( String name, value)
    int cid=1001; Query query=em.createQuery(&quot;select k from Candidate k where k.candidateid=:candId&quot;); query.setParameter(“candId&quot;, cid); Local Variable
  • Positional Parameters
    • Query parameters are prefixed with a question mark sign(?) followed by the numeric position of parameter.
    • To set the value of a parameter use the method setParameter ( int position, value)
    Query query=em.createQuery(&quot;select k from Candidate k where k.candidateid=?1&quot;); query.setParameter(1, cid);
  • update(U)
    • executeUpdate() – updates one or more entities
    Query query=em.createQuery( &quot;update Candidate cd set cd.DOB=:dob where cd.candidateid=:cId&quot;); query.setParameter(&quot;dob&quot;, dateOfBirth ); query.setParameter(&quot;cId&quot;, cid); int update=query.executeUpdate();
  • delete(D) Query query=em.createQuery(&quot;delete from Candidate cd where cd.candidateid=?1&quot;); query.setParameter(1, cId); int updateCount=query.executeUpdate() ;
  • JDBC EXECUTION VS JPQL EXECUTION Steps for JDBC with SQL Steps for JPA with JPQL Obtain database connection by using con=DriverManger.getConnection() Obtain an instance of EntityManager EntityManager em=emf.createEntityManager() Create a query statement Statement st=con.createStatement() Create a Query instance Query query=em.createQuery() Execute the statement ResultSet rs=st.executeQuery() Execute the query List rs=query.getResultList(); Retrieve database records using ResultSet Retrieve entities using List
  • Types of Queries
    • Named queries
    • Native SQL queries
  • Named Queries
    • Intended to be stored and reused.
    • Defined with the help of @NamedQuery annotation.
    • Attributes of @NamedQuery are
    • name -It represents the name of the query. It will be used with createNamedQuery method.
    • query -The query to be used
    @NamedQuery(name=&quot;findAllCandidates&quot;, query=&quot;SELECT cd FROM Candidate cd&quot;) Query findAllQuery = em.createNamedQuery(“ findAllCandidates ”); List candidates = findAllQuery.getResultList();
  • Multiple Named Queries
    • Multiple named queries can be defined using the annotation @NamedQueries
    @NamedQueries( { @NamedQuery(name = “findAllCandiadtes” query = “SELECT cd FROM Candidate cd”), @NamedQuery(name = “deleteAllCandiadtes” query = “DELETE from Candidate cd”) } )
  • Native SQL queries
    • SQL query that depends on the database
    • Example:Oracle, MySQL etc.
    • Calling a stored function from JPA is done using Native SQL queries
    • A stored function with an OUT parameter cannot be called using JPA
    • A stored function is invoked using a SELECT statement
    • A stored function called using a SELECT statement cannot contain DML statements (INSERT, DELETE, UPDATE)
  • Invoking a Stored Function using NativeQuery
    • create or replace function
    • sf_area (p_radius number)
    • return number
    • is
    • p_area number(10);
    • Begin
    • p_area:=p_radius*p_radius*3.14;
    • return p_area;
    • end;
    Query q=em.createNativeQuery (&quot;select sf_area(?1) from dual&quot;); q.setParameter(1, radius); List rs= (List)q.getSingleResult(); BigDecimal obj=(BigDecimal)rs.get(0); int i=obj.intValue(); System.out.println(i); // import java.math.BigDecimal Oracle Function Calling a function from JPA
  • Expressions and Operators (Self Study)
    • A complex query may require the use of expressions and operators
    • Usage is similar to SQL
  • JOINS IN JPQL
    • Joins in JPQL are same as in SQL
    • Join Query in JPQL will follow the syntax rules of JPQL.
    @Entity @Table(name=&quot;emp&quot;) public class Employee { @Id private int empNo; private String eName; private String job; private java.sql.Date hireDate; private int sal; private int comm; private int deptNo; //setter and getter } @Entity @Table(name=&quot;Dept&quot;) public class Department { @Id private int deptNo; private String dName; private String loc; //setter and getter } FOREIGN KEY PRIMARY KEY
  • RETRIEVING DIFFERENT ENTITIES USING JOIN
    • Query query=em.createQuery(&quot;select emp,dept from Employee emp, Department dept where emp.deptNo=dept.deptNo and (emp.eName like 'A%' or emp.eName like 'M%') &quot;);
    • List rs=query.getResultList();
    • int size=rs.size();
    • for(int i=0;i<size;i++) {
    • Object[] obj = (Object[])rs.get(i);
    • Employee emp=(Employee)obj[0];
    • System. out.print(emp.getEName()+&quot;
    • &quot;);
    • Department dept=(Department)obj[1];
    • System. out.print(dept.getDName());
    • }
    Each element in the list is array of objects The first array element refers to Employee entity The second array element refers to Department entity
  • JPQL functions(Self study)
    • CONCAT
    • SUBSTRING
    • LENGTH
    • CURRENT_DATE
  • Aggregate functions(Self study)
    • AVG
    • COUNT
    • MAX
    • MIN
    • SUM
  • Can you answer these questions?
    • What is the difference in using SQL with JDBC and JPQL in JPA?
    • What are the various techniques for setting the parameter of a query?
    • How to call a function using JPA?
  • Summary
    • Java Persistence Query Language
      • Introduction to JPQL
      • Interaction with the Database
      • Different queries in JPQL
      • Execution of JDBC and JPQL
      • Joins in JPQL
  • 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.”
  • 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
  • Calling a Procedure using NativeQuery (1 of 2)
    • A procedure can not be called using SQL expression.
    • Native SQL query must be used to call a procedure.
    • The syntax to call a procedure is similar to the callableStatement in JDBC.
    • The Procedure with an OUT parameter cannot be called using JPA
    • .
  • Calling a Procedure using NativeQuery (2 of 2)
    • create or replace procedure
    • sp_area(p_radius number)
    • is
    • p_area number(10);
    • Begin
    • p_area:=p_radius*p_radius
    • *3.14;
    • Insert into area values(p_radius,p_area);
    • end;
    EntityTransaction et=em.getTransaction(); et.begin(); int radius=10; Query q=em.createNativeQuery (&quot;{call sp_area(?1)}&quot;); q.setParameter(1, radius); q.executeUpdate(); et.commit(); Oracle Procedure Calling a Procedure in JPA