Monday, June 25, 2012

Quick Reference For JPA Interviews:



The example used for ONE-TO-MANY relationship is as follows:  Order and Order Items.

Order class has a Set of Order Items, and the OrderItem has the Order object to which this order item belongs to.

 public class Order {
@OneToMany(mappedBy = "Order")
private Set<OrderItem> orderItems = new HashSetOrderItem>();
}

public class OrderItem{
            @ManyToOne
       @JoinColumn(name = "BOI_ORDER_ID")
       private Order Order;
}


1.       As you see OneToMany does not mention the fetch type. This is because, OPEN JPA, by default, lazy loads the Collections; so does Hibernate 3.0.

2.       Fetch Type Eager makes sense for most of the ManyToOne, however, in case the One Side i.e. the parent Entity, is a big object and it is not required for processing most of the times, it would be better to set the FetchType=Lazy, as follows

@ManyToOne(fetch = FetchType.LAZY)

3.       Setting FetchType Lazy also makes sense for very large attributes, typically clobs. This can be done with the Basic annotation e.g. a contract document of a order, let us assume it a clob in the db.

public class Order {
@Basic(fetch = FetchType.LAZY)
@Coulmn(name =”ORDER_CONTRACT)
private String contract;

}

4.       JPA default assumes that the foreign key is a Primary Key in the reference table. However, though not often, there are foreign keys that are Unique in the reference table. To accommodate this, JPA provides referenceColumnName in JoinColumn annotation.

E.g. If the social security number is a unique key in the employee table, EMP_SSN_ID, (not a Primary key for obvious reasons) , this key is reference to a table that gather data to be sent to Social Security Dept. for processing. In this case, the social security number will be a foreign key in the ssn_dept table.
The Many-to-One side of this relationship will be defined as:

@ManyToOne
@JoinColumn(name="SSN_ID", referencedColumnName="EMP_SSN_ID")
private Employee employee;
     
5.       Many-to-One and CascadeType: In some scenarios it makes sense in setting CascadeType to Persist on a Many-to-One. This means when a many-to-one is persisted, the One side is automatically persisted. E.g. Order and a Customer, when an Order is Persisted it makes sense that the customer is automatically persisted too.

Example:

   public class Order {
            @OneToMany(mappedBy = "order")
       private Set<Customer> customers = new HashSet<Customer>();
   }

6.       Difference between optional and nullable: The main difference is the scope at which these are applied. Optional is validation before the data is sent to Database, where as nullable is applied to a database column when database tables are generated from JPA.
The optional throws InvalidSateException.

 This is how the annotation is applied, please not optional is part of Basic and nullable is part of column.
       public class Customer{

@Basic(optional=false)
@Column(name = “CUST_NAME”, nullable=true)
  private String custName;
}
Note that in the absence of the Basic annotation, if custName contains null, it is passed to the database and a database exception will be thrown at the time of insert/update.
The nullable will have no effect on insert/update, it will only play a role when the db table is created.
      
Most reverse engineering tools, do not generate the Basic (nullable=false) or Column(nullabe=true) for not null columns in the db.

7.       Validation of Attributes Before sending to Database: The optional validation can be done using @Basic as mentioned earlier. For any other validation (size etc.), JPA does not provide any annotations. If this is a requirement, use Bean Validation API, jsr 303.

8.       Consequences of Lazy Loading outside the Entity Manager Context: 

The consequences depend on the underline implementation of lazy initialization. Hibernate uses proxy objects at the runtime, whereas openjpa enhances the entity classes before runtime.

Hibernate throws LazyInitializationException, while openjpa returns null and hence a NPE is likely to be thrown if there is no check for null.
Consider the code below in the context of our order->orderItem example.

Set<OrderItems> sitems = order.getOrderItems() ;
 System.out.println( items.size() );

When the code above is executed   outside of Entity Manager, (and of course Items were not retrieved when Order was returned from entity manager), Hibernate will throw LazyInitializationError; while openjpa will return null, and hence a NPE will be thrown.

A good practice for retrieving collections outside of the Entity Manager context is using NamedQueries.

9.       Difference between persist and merge: This is significant for Hibernate users, who typically use saveOrUpdate. In case of saveOrUpdate, Hibernate attaches the object (passed to the method) to the context. In case of JPA, persist attaches the object (passed to the method) to the context whereas merge does not. The object returned by merge is attached to the context.
It can be better explained with this example.

  Order order = new Order(); // A new order is created.
  order.setCustName(“ ABC Inc.”);
   entityManager.persist(order);
  System.out.println(“ New Order id: “ + order.getId()); // ID is generated at the time of insert.

In the above example, if the id generated was 1000, it will print
 New Order id : 1000

       Now let us make some change to the above code, and use merge as follows.

  Order order = new Order(); // A new order is created.
  order.setCustName(“ ABC Inc.”);
  Order ordRef =  entityManager.merger(order);
  System.out.println(“ New Order id: “ + order.getId()); // ID is generated at the time of insert.

  System.out.println(“ New Order Ref id: “ + ordRef.getId()); // ID is generated at the time of insert.

Again, if the id generated was 1000, it will print
New Order id:  0 (If Id was initialized as an instance field )
       New Order Ref id: 1000

Note: In case of persist, the object order was synchronized with the db, where as in case of merge, the order object was copied, and the ordRef object , the objet returned had the id, since this returned object was the object from the context.
The best practice for save/update is as follows: (sOrder is the object to be save/updated)

 Order rOrder = em.find(Order.class, sOrder.getId());
              if (rOrder == null) {
                     em.persist(sOrder);

              } else {
                     em.merge(sOrder);
              }

10.   TableGenerator for ID Column: I prefer this over all other ID generators, for various reasons. First and foremost it is truly database independent. Secondly the sequence’s current status is accessible and visible any time.
This is how it works:  Generate a table in the db, with a minimum of two columns, key and value. Key is similar to the sequence name and value is the current value.

  create table seq_id_gen (tab_key varchar2(100), key_value number);
   Insert into seq_id_gen (“ORD_PK”, 1);
   Insert into seq_id_gen (“ORD_ITEM_PK”, 1);

Now for Order and OrderItem, the Id annotations will be:

      public class Order {
@Id
       @GeneratedValue(strategy = GenerationType.TABLE, generator = "ORD_PK")
@TableGenerator(name = "ORD_PK", table = "SEQ_ID_GEN", pkColumnName = "TAB_ _KEY", valueColumnName = "KEY_VALUE", pkColumnValue = "ORD_PK", allocationSize = 10)
       @Column(name = "ORD_ID")
   private long ordId;
      }

       Please note the values of: pkColumnName (The column that stores the seq name)
       valueColumnName: (The column that stores the current value of the sequence)
      pk_column_value: Identifies the row that will be used.
      allocation_size is the cached number of sequence numbers.

           public class OrderItem{
@Id
       @GeneratedValue(strategy = GenerationType.TABLE, generator = "ORD_ITEM_PK")
@TableGenerator(name = "ORD_ITEM_PK", table = "SEQ_ID_GEN", pkColumnName = "TAB_ _KEY", valueColumnName = "KEY_VALUE", pkColumnValue = "ORD_ITEM_PK", allocationSize = 10)
       @Column(name = "ORD_ID")
   private long ordId;
      }

     It is not mandatory to have the generator name same as the pkColumnValue, I just find it   convenient to track.

      What happens when a new record is persisted?

As you would expect, for Order, 1 is assigned to order.id and the key_value is updated to 11 fro the row having tab_key = ORDER_PK.


    OPEN JPA selects the value using Select ..for update when available or locks the table is required.           
    In either case the row is locked and hence does not pose any concurrency issues.

    Also note, if the INSERT fails (in this case for Order) then the corresponding sequence number is     lost, it is not rolled back.

Tuesday, November 29, 2011

why I want to learn Mongo

I go long back with the relational databases, since Oracle 6. It was easy to understand and even easier to model. Then I got interested in Java and more in Object Thinking, and of course began to feel the constraints of relational implementation, especially when it came to the "composite" relationship, i.e. when a child entity does not have its own life cycle, and its life cycle is completely dependent on the parent entity, storing it in another table, defining a PK for it (often times a seq number) and making a join for every operation feels a lot of unnecessary work. I understand that in the relational paradigm for the validity and integrity of the data this is the best way. However I always felt there should have been a better way to work with it. With Oracle 9 or may be 8, came the varray and nested tables, but all the db operations with those new structures were pretty clumsy and did not really appeal or fit the Java side, the object oriented view of the data. 
About six months ago I got assigned to a social networking project, customizing of a social networking portal and the short comings of RDBMS I always  suddenly became prominent. That is when I started to learn about the NOSQL databases. The first I read about was the Big table of google, then the simpledb of amazon, and then couchdb. I then found out that all NOSQL is not equal.
Big table type of nosql can essentially have a different schema for each row, Simple DB falls in the category of simple key value pair storage and couch is more of a document style database. Lately I also came across the fourth category, Graph databases, the only one I know a little bit about is Neo4j, a purely java based nosql db.
From whatever I read, it is clear the big table and simple db would be very easy to use for specific applications but not many applications would fall in those categories. Document based  db on the other hand felt the closest to the RDB. Once I came to this conclusion I started reading more and some how settled on the idea of learning Mongo db, why?
1. It was easy to download and get it running.
2. The documentation gave parallels between the RDB and Mongo.
3. The parallels are not only conceptual but also in terms operations.
4. It has drivers for many languages, especially for Java, which means I dont have to learn a new language in order to learn Mongo.
5. There is even a JPA project Morphia for Java-Mongo.
6. The shell is javascript, being a web developer I am pretty conversant with it.
7. NYC has a good meetup group of mongo.
8. The mongodb site is pretty dynamic
All in all, I feel very comfortable with Mongo. I could get it running on windows.

All the literature I have read so far, I dont think learning the commands or even accessing the db via drivers will difficult, the real challenge will be the database modeling. I have a feeling that I can still continue thinking the world in terms E-R but I will have to map them in a different way than in RDB.
I hope to work on a good project and continue to think loudly of my mongo expereinces.