Thursday, November 3, 2011

Rolling Back Transactions

While doing a spot check on code and configuration – I noticed that the developer wasn’t throwing a runtime exception nor was he setting rollbackOnly in a CMT EJB.

I was told that any exception will rollback a transaction and it is not possible to setRollbackOnly, and there are only 4 types of transaction attributes on CMT. Wrong, wrong and wrong.

1. If your code throws an application exception – the container expects the bean to handle it. However, if your bean throws a runtime exception (or subclass), like javax.ejb.Exception – the container will rollback the transaction.

2. If you don’t want to throw RTEs all around your code – and/or you have massive catch all exception code blocks, you should context.setRollbackOnly – to rollback transactions.

3. There are various transaction attributes – 6 to be exact: Requires, Requires New, Supports, Not Supported, Never & Mandatory. Never and Mandatory are opposite to one another. Requires starts a transaction if not called with one, Mandatory will throw an exception if called without a transaction, Supports will use one if there is one, but won’t complain….rest are self explanatory.

What’s most important about Transactions are how the transaction propagates in both directions (commit and more importantly rollback)

Java EE 5–No Entity Beans!

I’ve always done ORM with HIbernate –and it helped a lot with cardinality (besides ORM general features).

1:1::Married Couple (there are cultural and religious exceptions)

1:n:: Order: Line Item

n:1:: Line Item: Order

n:n:: Course: Student

Regardless of cardinality, entities should never be non-singular from a naming convention stand point.

In Bidirectional relationships – the inverse side must refer to its owning side via the mappedBy element.

In n:1, the many side always owns the relationship. In n:n – it doesn’t matter.

All in all the beauty of Java Persistence API is that it has all the features that Hibernate had – and then makes things a lot simpler with Annotations. I never was a fan of annotations when they first surfaced, but I have slowly come to like it. I like the encapsulation it provides.

You can mix non-entity super classes with entity super classes, use polymorphic associations, queries etc. It is surprisingly flexible.

Three basic strategies remained consistent in ORM land – 1 table per class (or class per table) – usually you will have a database structure before you have the object structure.