Examples or Uses Cases to explain EJB Transaction Attributes

cwash picture cwash · Nov 18, 2009 · Viewed 13.3k times · Source

There are some good explanations of EJB Transaction Attributes (and annotations) out there, for example, OpenEJB's.

But sometimes when I try to cover this with someone who hasn't worked with many transactional resources, I see their eyes start to glaze over.

So my question - how would you explain EJB Transaction Attributes to your grandmother?

  • Required
  • RequiresNew
  • Mandatory
  • NotSupported
  • Supports
  • Never

I'm thinking a contrived example, analogy, or a concise real-world use case would be helpful.

Answer

Miguel Ping picture Miguel Ping · Nov 19, 2009

You can think of them in terms of Collaboration. Let's say you are a chef, and you have a dozen ovens to work with. You need to bake some cakes. For this example, you are the called method, the oven is the transaction and the your boss is the caller.

  • Required: if your boss tells you to bake some cakes without telling you what oven you use, you just go ahead and pick one. At the end, you close the oven, making sure nobody else can use it.
  • Requires New: You will always bake the cakes on a free oven you choose. If you're in the middle of the process of baking some cakes and your boss tells you to bake another batch, you interrupt the current baking process, go and bake some cakes at a new oven, the resume the baking for the old ones.
  • Mandatory: You are a dumb cook. Your boss always have to tell you what oven you have to use. If your boss doesn't tell you what oven to use, you shout back "stupid!".
  • NotSupported: Think of this as doing a dessert that doesn't need the oven. If you are in the middle of baking some cakes at the oven, you stop that, create the dessert, and the resume the cake baking.
  • Supports: This is more suited to a cook's helper. You are the helper. If the main cook asks you to bake a cake with oven X, you just do that. If he asks you to do a dessert, you just do that. The main difference in regards to the other ones is that you never ask any question nor choose to do anything. You just follow orders.
  • Never: This is yet another dumb cook. If your boss asks you to do a dessert while you're in the middle of baking a cake, you shout back and say "I quit!". No cake is ever baked. So your boss has to be careful and only ask you to bake some cakes when you are not baking any cakes.

Hope that helps.