1 / 30

Training - Day 3

Training - Day 3. OJB. OR Mapping is the mapping of relational database tables to objects (Java Objects in our case) Many OR Mapping tools available Hibernate iBatis OJB UIS supports Apache OJB Current version: 1.0.4. What is OR Mapping?.

yair
Download Presentation

Training - Day 3

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. Training - Day 3 OJB

  2. OR Mapping is the mapping of relational database tables to objects (Java Objects in our case) Many OR Mapping tools available Hibernate iBatis OJB UIS supports Apache OJB Current version: 1.0.4 What is OR Mapping?

  3. Open source project sponsored by the Apache Project Makes working with a database feel like working with an Java object model SQL is seldom used OJB generates the SQL Criteria objects Apache OJB

  4. Store and retrieve Java objects to/from any JDBC compliant RDMS No special interfaces needed for your OJB objects – transparent persistence Object graphs can be persisted by persisting the root object Mapping support for 1:1, 1:n, and m:n associations OR Mappings defined in an XML repository Can use multiple databases Lazy loading via proxies (JDK or CGLIB) Support for polymorphism and extents Multiple sequence manager implementations Connection pooling and reuse of prepared statements JTA and JCA integration Optimistic (via number or timestamp) and pessimistic locking supported Support for object caching Some of the features…

  5. Persistence Broker (PB) Low level kernel API Foundation of the others below ODMG Object Data Management Group Persistence 3.0 Full support JDO Java Data Objects Partial support OTM Object Transaction Manager API or tool to build other tools on Specific to OJB Supported APIs

  6. Kuali supported API Low level API compared to OTM, ODMG or JDO, but still very easy to use Store, update, delete, and retrieve objects or collections of objects More on the PB after we learn how to configure OJB and map relationships Persistence Broker

  7. Usually found on the root of the project classpath When upgrading OJB from any version, this file should be replaced and updated Key points Location of the repository.xml file How to obtain database connections How to obtain proxies How to manage transactions OJB.properties

  8. Let’s take a look at a real OJB.properties file Example

  9. repository.xml usually on the root of the project classpath A DTD is also needed Good idea to break up the contents of repository.xml for easy reuse (testing) repository_user.xml : OR Mappings repository_database.xml : Database config The Repository Mapping

  10. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE descriptor-repository PUBLIC "-//Apache Software Foundation//DTD OJB Repository//EN" "repository.dtd" [ <!ENTITY database SYSTEM "repository_database.xml"> <!ENTITY user SYSTEM "repository_user.xml"> ]> <descriptor-repository version="1.0" isolation-level="read-uncommitted" proxy-prefetching-limit="50"> <!-- include all used database connections --> &database; <!-- include user defined mappings here --> &user; </descriptor-repository> repository.xml

  11. <!-- Datasource example --> <jdbc-connection-descriptor jcd-alias="MYDB" default-connection="true" platform="Oracle9i" jdbc-level="3.0" batch-mode="false" useAutoCommit="1" ignoreAutoCommitExceptions="false" testOnBorrow="true" testWhileIdle="true" testOnReturn="true" validationQuery="select 1 from dual"> <object-cache class="org.apache.ojb.broker.cache.ObjectCachePerBrokerImpl"> </object-cache> <sequence-manager className="org.apache.ojb.broker.util.sequence.SequenceManagerNextValImpl"> </sequence-manager> </jdbc-connection-descriptor> repository_database.xml

  12. Where you define your table to object mapping <class-descriptor class="edu.iu.uis.train.domain.User" table="TRN_USR_T"> <class-descriptor>

  13. A database column, or object property <field-descriptor name=”username" column=”usr_nm" jdbc-type="VARCHAR" /> <field-descriptor>

  14. Primary keys primarykey=“true” Auto-incrementing PK autoincrement=“true” Will use the Sequence Manager that you have configured If using Oracle sequences, you can set the sequence name: sequence-name=“some seq” Locking field (we use optimistic locking – fast, data integrity only checked on an update) locking=“true” Need to store a hidden locking field on JSP pages Long – incremented each time the column is updated Long is recommended because of Oracle Other possibilities are Integer and Timestamp A few special fields

  15. JDBC Type Java Type CHAR String VARCHAR String LONGVARCHAR String NUMERIC java.math.BigDecimal DECIMAL java.math.BigDecimal BIT boolean / Boolean BOOLEAN boolean / Boolean TINYINT Byte / byte SMALLINT Short / short INTEGER Integer / int BIGINT Long / long REAL Float / float FLOAT Double / double DOUBLE Double / double BINARY byte[] VARBINARY byte[] LONGVARBINARY byte[] DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp CLOB Clob BLOB Blob ARRAY Array DISTINCT mapping of underlying type STRUCT Struct REF Ref DATALINK java.net.URL JAVA_OBJECT underlying Java class JDBC Types

  16. 1:1 Relationship <reference-descriptor name=”movie" class-ref="edu.iu.uis.train.domain.Movie" auto-retrieve="true" auto-update="false" auto-delete="false" > <foreignkey field-ref=”movieId" target-field-ref="movieId"/> </reference-descriptor> <reference-descriptor>

  17. 1:n Relationship or m:n Relationship <collection-descriptor name=”userCollection" element-class-ref="edu.iu.uis.train.domain.User" auto-retrieve="true" auto-update="true" auto-delete="true" proxy="false"> <inverse-foreignkey field-ref=”userId" target-field-ref=”userId"/> </collection-descriptor> <collection-descriptor>

  18. Let’s take a looks at this file in the exercises project repository_user.xml

  19. Open repository_user.xml and complete the TODO items Need DDL for columns and types Need domain objects for attribute names (which are mapped to the columns) Exercise: Time to map your business objects

  20. You can use the PB to: Query Insert and update Delete It can also tap into database transactions, which you should probably do just about all, if not all, the time Getting back to the PB API

  21. public static void storeProduct(Product product) { PersistenceBroker broker = null; try { broker = PersistenceBrokerFactory.defaultPersistenceBroker(); broker.beginTransaction(); broker.store(product); broker.commitTransaction(); }catch(PersistenceBrokerException e) { if(broker != null) broker.abortTransaction(); // do more exception handling }finally { if (broker != null) broker.close(); } } Saving an object

  22. public static void storeProducts(List products) { PersistenceBroker broker = null; try { broker = PersistenceBrokerFactory.defaultPersistenceBroker(); broker.beginTransaction(); for (Object productObj : products) { Project product = (Product) productObj; broker.store(product); } broker.commitTransaction(); } catch(PersistenceBrokerException e) { if(broker != null) broker.abortTransaction(); // do more exception handling } finally { if (broker != null) broker.close(); } } Saving multiple objects

  23. public static void storeProduct(Product product) { PersistenceBroker broker = null; try { broker = PersistenceBrokerFactory.defaultPersistenceBroker(); broker.beginTransaction(); broker.delete(product); broker.commitTransaction(); }catch(PersistenceBrokerException e){ if(broker != null) broker.abortTransaction(); // do more exception handling }finally { if (broker != null) broker.close(); } } Deleting an object

  24. You can build up a template object and query You can use raw sql if you need to bypass OJB You can use a Criteria object Recommended way This is the only way I will demonstrate for now, but there’s great docs on the OJB website if you want to try something else Querying in OJB

  25. public static Collection getExpensiveLowStockProducts() { PersistenceBroker broker = null; Collection results = null; try { broker = PersistenceBrokerFactory.defaultPersistenceBroker(); Criteria criteria = new Criteria(); criteria.addLessOrEqualThan("stock", new Integer(20)); criteria.addGreaterOrEqualThan("price", new Double(100000.0)); QueryByCriteria query = new QueryByCriteria(Product.class, criteria); results = broker.getCollectionByQuery(query); } finally { if (broker != null) broker.close(); } return results; } A simple query

  26. You can add just about any kind of “criteria” to build up an SQL statement Let’s take a look at the API http://db.apache.org/ojb/api/org/apache/ojb/broker/query/Criteria.html More about the Criteria

  27. public static boolean sellOneProduct(Integer stock) { PersistenceBroker broker = null; boolean isSold = false; try { broker = PersistenceBrokerFactory.defaultPersistenceBroker(); Criteria criteria = new Criteria(); criteria.addLessOrEqualThan("stock", stock); criteria.addGreaterOrEqualThan("price", new Double(100000.0)); QueryByCriteria query = new QueryByCriteria(Product.class, criteria); Product result = (Product) broker.getObjectByQuery(query); if (result != null) { broker.beginTransaction(); result.setStock(new Integer(result.getStock().intValue() - 1)); broker.store(result); broker.commitTransaction(); isSold = true; } } catch(PersistenceBrokerException e) { if(broker != null) broker.abortTransaction(); // do more exception handling } finally { if (broker != null) broker.close(); } return isSold; } Updating an object

  28. It’s time to write your first DAO You shouldn’t need to extend any files, just implement the MovieDAO interface Use eclipse to do this when you create the class and it will create all of the methods for you Let’s do this part together Exercise: The MovieDAOImpl

  29. Now that you’ve seen how the PB API works, there’s a much better way to work with OJB We will see more of this when we talk about Spring A better way to do all this

  30. Object Relational Bridge http://db.apache.org/ojb/ OJB Tutorials http://db.apache.org/ojb/docu/tutorials/summary.html References

More Related