The Codex of Business Writing Software for Real-World Solutions 2.pptx
Odtug2011 adf developers make the database work for you
1. ADF Developers – make the database work for you ODTUG Kaleidoscope 2011 – Long Beach, California Luc Bors, AMIS, The Netherlands
2. Desktop Browser-Based Metadata Services (MDS) Oracle ADF – Role of the Database JSF JSP Office ADFSwing Mobile View ADF Faces JSF Struts ADF Controller Controller ADF Binding Model Business Services EJB BAM ADFbc Portlets BI BPEL Web Services Java Data Services Database Web Services Legacy Systems Apps Unlimited
3. “We could also do that in the database” in the database? Huh? RDBMS ≈
8. Database Strengths Integrity Fine grained (data) security and auditing Data Retrieval joining tables together, leveraging indexes hierarchical, network-like traversals advanced analytics, historical queries, mining Aggregation and Sorting Complex & Massive Data Manipulation
9. RDBMS not always exclusively accessed through one Java API SOA, ESB, WebServices Database Batch Bulk Processes Standard Applications LegacyApplications Data Replication & Synchronization
10. Database Triggers – decorating Data Manipulation Triggers execute before or after Insert, Update or Delete of database records insert, update, delete Before Insert trigger: sal=… Employees
11. Purpose of triggers Set default values on new records if :new.job=‘SALESMAN’ then :new.comm = 1000 Calculate & Derive values upon insert, update or delete Notify third parties of data manipulation Perform complex validation on the data changes applied by the transaction Per Department: Max Salary < 1.8 * Average Per Manager: #subordinates < 15
12. ADF BC refreshing Entity Objects after triggers have applied new values Entity Object Employee (leveraging: returning <column> into : bind) post Before Insert trigger: sal=… Employees
13. Aggregation & Rollup Data for reporting purposes can be prepared by database queries Including aggregations(max/min/avg/count/sum) and Sub Totals and Grand Total and String Aggregation
14. Dynamic Aggregation through Non-conventional use of bind parameters Bind parameters are typically used in the WHERE clause of a SQL query However: they can also be used in the SELECT, ORDER BY and GROUP BY sections A combination of CASE and bind parameters in the GROUP BY can provide interesting options DynamicAggregation
16. Sub and Grandtotals with Rollup Rollup instructs databaseto aggregate at every levelstarting from the right deptno, job deptno (grand total) Also see: Cube GroupingSets
18. Analytical Functions – spreadsheet-style row processing Analytical Functions allow SQL queries to perform inter-row comparison & aggregation For example: in a single query, for each employee show salary rank in department and job show salary difference with colleague next higher in rank (on the list per department) show average salary in the department show csv list of colleagues in department
22. Flashback Versions Retrieve all states each record has been in Every transaction that touched a row left a version of the record Pseudocolumns: xid, operation, start time, end time Use constants minvalueand maxvalueto retrieve all versions Flashback versions make journaling tables redundant
25. Embedding Historic Data in ADF Application Where Clause in (read only) ViewObject can include FLASHBACK operators AS OF and VERSIONS BETWEEN Bind parameters can be used to set the point in time or the historic time interval A time selector can be used to visually set the interval Scalar subqueries can be used for ‘in line comparison to a certain point in time’ “How much higher/lower is the salary than at the selected date?”
28. ADF Model & Tree Data Binding Create hierarchical relation between multiple ViewObject or (POJO) Collection Bindings Tree Data Retrieval retrieves collections in several steps i.e. multiple queries Data is cached Data is only queried when required (given the expansion level of the tree) Alternatively: have the database do the heavy tree lifting: Database has optimized tree algorithms Starting at any node in the tree or network Drilling down to the specified number of levels Order siblings within parent Indicate leaf and parent nodes; detect cycles
29. Retrieving Hierarchical data sets with single SQL statements Database has optimized algorithms Starting at any node in the tree or network Drilling down to the specified number of levels Order siblings within parent Indicate leaf and parent nodes; detect cycles EMPID ENAME MGR DEPTNO LEVEL --------------- ---------- ---------- ---------- ---------- 7839 KING 10 1 7698 BLAKE 7839 30 2 7499 ALLEN 7698 30 3 7900 JAMES 7698 30 3 7654 MARTIN 7698 30 3 7844 TURNER 7698 30 3 7521 WARD 7698 30 3 7782 CLARK 7839 10 2 7934 MILLER 7782 10 3
30. Oracle 11g and ANSI SQL for hierarchical query with employees (empno, name, mgr, hierlevel, path) as ( select empno, ename, mgr, 1, ename from emp where mgr is null union all select e.empno, e.ename , e.mgr, m.hierlevel + 1 , m.path||'/'||e.ename from emp e join employees m on (m.empno = e.mgr) ) select * from employees
32. Steps for filter driven querying Determine the values to filter on Create a query to retrieve for all filters Every individual value and the # occurrences The where-clause to apply on the real VO The label for the filter Create a managed bean to apply selected filtersto ViewObject Create page that displays filters and selected dataand handles filter “clicks”
33. Encapsulate Database specific SQL in a View API Views – for encapsulation of data model, multi-table join, (advanced) SQL hiding, authorization rules Note: a view looks like a table to the client View
34. The read-only cursor API A Cursor is a reference to a query result set Database can open a cursor for a SQL query And return it to the application to fetch the rows from Cursor == JDBCResultSet A cursor can be nested: containdetails … JDBC ResultSet while rs.next { … } cursor Stored Procedure Departments SQL Employees
37. Providing a ‘business object’ API DML API: a View – aided by an Instead Of trigger Insert of one new row inUSERS_VW (e.g. a JPApersist operation) can actually be four new records USER, PERSON, EMAIL_TYPEEMAIL_ADDRESS USERS USERS EMAIL_TYPE Instead Of DML trigger * * PERSONS EMAIL_ADDRESSES * *
38. Instead of Insert Trigger on USERS_VW (1/2) create or replace trigger handle_insert_users_trg instead of insert on users_vw for each row declare l_psn_id persons.id%type; begin insert into persons ( id, first_name, last_name, address, ...) values ( nvl(:new.id, central_seq.nextval),:new.first_name , :new.last_name, :new.address, ...) returning id into l_psn_id; insert into user_accounts ( id, psn_id, username, password) values ( central_seq.nextval ,l_psn_id , :new.username , :new.password);
39. Instead of Insert Trigger on USERS_VW (2/2) ... insert into email_addresses ( id, psn_id, ete_id, address) values ( central_seq.nextval , l_psn_id , ( select id from email_types ete where ete.address_type = :new.primary_email_type ) , :new.primary_email) ; end handle_insert_users_trg;
40. Creating a new user User Administration USERS First Name Last Name Molly Warhol Username Password mwarhol ****** USERS EMAIL_TYPE Instead Of DML trigger Address City 1 Slickroad Las Vegas Telephone Mobile 5551212 43219876 * Email Email type mw@un.org Business PERSONS EMAIL_ADDRESSES Activation 24-may-2008 * *
41. ADF BC and Complex Views with Instead of Triggers Override the lock method in the ViewObjectImpl Default implementation will attempt select … from <view> for update ofWhich is not allowed on Views with an instead of trigger
44. HTML 5 dbEdge Cache JEE Application Server Cache Cluster Fail-Over (Session State) Result Store Write Behind Client Result Cache RDBMS Result Cache Materialized View
46. Cache Refresh triggered by DB Oracle RDBMS invokes Java Listener with event details POJO / ADF BC Register DatabaseChangeNotification SQL query PL/SQL
47. Shared Application Modules Normal Application Module instances are session level – i.e. not shared across (web) sessions Shared Application Module instances are shared across sessions like an Application Scope Managed Bean Used for Static Data Sets: Look Up Data and Reference Tables Sessions can reuse the data from a shared Application Module without having to access the database And loading the same data in session level memory scope View Accessors can be used to access data in the Shared Application Module’s VOs For example for use in LOVs or Validation Rules
49. Auto Refresh for ViewObjects ViewObjects in a Shared Application Module can be registered for auto refresh Typically such application wide VOs are near-static Whenever the underlying data set changes (in the database), the VO rowset should be refreshed By setting Auto Refresh (to true) for the ViewObject, the VO will be refreshed whenever the database is changed ADF registers the VO query with the Database (11g) Result Set Change Notification mechanism through JDBC Note: the VO should not have an Order By clause nor select a Date column
50. Steps for auto refresh enabling Create Shared Application Module New application module that is added to list of Application Level instances in the Project properties Create the ViewObject that queries the ‘static data’ and add to Shared Application Module Set the Auto Refresh property to true for VO instance Database must be 11g (and have parameter compatible set to 11.1.0 or above) database user must have the Change Notification privilege To piggyback changes to page, set changeEventPolicy to autoPPR on data binding
51. Set Auto Refresh for ViewObject Set Auto Refresh for ViewObject Grant Change Notification todatabase user
58. JEE Application Server Enterprise Service Bus ADF Application Web Service ? Database informing and leveraging the middle tier HTTP calls using the UTL_HTTP package
59. Asynchronous processing Execute stored procedures or command scripts (O/S) in the background – using a job Free up the synchronous thread Return control to invoking Java application Ideal for Fire-and-Forget (one way) calls Results can be returned asynchronously Via Queue, Table, Database Query Result Change Notification, HTTP call, Email,… Create a Job in the Oracle Database using: package dbms_scheduler
60. Other Database Features worth investigating Virtual Private Database & Fine Grained Authorization XMLType, XMLDB & FTP/HTTP/WEBDAV server Object Types and Collections Data type Interval & Time Zone support Fine Grained Auditing System Triggers, for example “after logon” (Global) Application Context Autonomous Transaction Advanced Queuing (& JMS interaction) Creating advanced job execution schedules Edition Based Redefinition (versioning of database objects) Statistics and Data Mining Scalar Subqueries
61. Summary & Conclusions Databases can do much more than ADF applications can benefit! Strike the right balance: Leverage database forwhat it can do best Make ADF and Database work together in a smooth way
select ename, sal, deptno, job, rank() over (partition by deptno order by saldesc) sal_rank_in_dept, rank() over (partition by job order by saldesc) sal_rank_in_job, lag(sal,1) over (partition by deptno order by saldesc) diff_with_next_higher_in_dept, listagg(ename, ',') within group (order by ename) over (partition by deptno) colleaguesfrom emporderby deptno, saldesc
Cache – spreekuit: kasjeKastjesBrowser: Client (browser, cookie or Java Script memory; HTML 5 offers persistent, cross session local db like storage)App Server : Edge (WebServer)JVM (and cluster)Cross cluster shared cachedb or memory gridDatabase (not requery at least)
Screenshot:Frank sends email to Maggie – with a query on EmployeesAfter some time, a response is sent to this particular email – by the queue listener using the JSP to send(list of employee data, corresponding with “query”)