Data AccessCore JavaApp FrameworksViewTestingBuildingDeploymentDev ToolsSecurityOpinions

Wednesday, December 9, 2009

Why you should look into ORM, if you haven't already?

In my last posting, I got clobbered by the blogosphere concerning my posting "Data Access: Plain JDBC vs. ORM".

I feel that the title was misleading, however, I do think that I do make some valid points about the shortcomings of authoring a data tier without the assistance of some type of ORM.

It is my opinion that, yes, there are many applications out there that still use raw JDBC as the primary method of accessing a data source in their data tier.

With that being said, I was targeting this article to those programmers that still write data tiers using raw JDBC, and was thinking of following up with some simple posts and tutorials on ORM's like Spring JDBC and Hibernate.

Without further ado, I am going to repost my thoughts and concerns.

Why you should look into ORM, if you haven't already?

A developer's goal when writing data access code is to properly contain the responsibilities of all data access operations. Leaking data access operations into the application is referred to as leakage of data-access details and has some adverse affects when the application has to adapt to changes on the data side.

Let's take a look at a method that uses raw JDBC:

public class UserRegistrationJDBC {

   private javax.sql.DataSource dataSource;

   public int getUserRegistrationCount() throws MyDataAccessException {

      java.sql.Connection connection = null;
      java.sql.Statement statement = null;
      java.sql.ResultSet resultSet = null;
         connection = dataSource.getConnection();
         statement = connection.createStatement();
         resultSet = statement.executeQuery(
         return rs.getInt(1);
      }catch(java.sql.SQLException sqle){
         throw new MyDataAccessException(e);
         if(resultSet != null){ 
            try{ resultSet.close() }
            catch (java.sql.SQLException sqle){ sqle.printStackTrace(); }
         if(statement != null){ 
            try{ statement.close() }
            catch (java.sql.SQLException sqle){ sqle.printStackTrace(); }
         if(connection != null){ 
            try{ connection.close() }
            catch (java.sql.SQLException sqle){ sqle.printStackTrace(); }
Let's look at some technical details contained within the code above:
  • The call to getConnection() on the javax.sql.DataSource object can be problematic because it obtains its own database connection. For example, suppose we wrote all our data access methods like the one above, even for inserts and updates. Imagine attempting to persist multiple records, perhaps on the completion of an order, something with an invoice, shipping details and billing details. If one of those transactions fail for some unexpected reason, how would you rollback the transactions? Obtaining a connection from the pool will only rollback the last transaction, leaving you to hand implement the rollback. It becomes even worse if the set of transactions spans multiple data sources.
  • The call to createStatement() is problematic as well. All sql should be rendered using a java.sql.PreparedStatement() for improved performance via caching. While this is more of a practice and learned through experience, using raw JDBC leaves the programmer open to these types of mistakes.
  • Catching a java.sql.SQLException is required by the JDBC API as it is it's only exception type and typically reveals little about the root cause of your error. Wrapping it with the unchecked exception MyDataAccessException, adds little value, only that your calling code does not have to catch it. Your application code now is restricted in how it can deal with specific data access errors.
  • The finally block contains the closing of all resources used in the method, which makes it impossible for other methods to reuse it.
Poor handling of the concerns above can lead to:
  • Resource exhaustion - loss of connection availability and loss of memory from improperly closed result sets and statements.
  • Poor performance - due to Statement vs. PreparedStatement as mentioned above.
  • Inappropriate connection life cycles - any operation where more than one SQL statement is executed can reuse connections and other resources for more appropriate life cycles. Even with connection pools, we should be careful not to spend CPU cycles and memory on obtaining and releasing connections.
To elaborate even further the inappropriate connection life cycles point, consider where a user registration is added with a payment for the registration. We would want to ensure that all the data access operations occurred or none at all. In a more appropriate world, we want to demarcate these operations at a transaction level, enabling the reuse of all related resources.

The goal of many ORM's are to effectively handle the leakage of data access details into the view tier. In addition, they support:
  • Transaction Demarcation - a mechanism to declare when transactions start and end, and support rollback.
  • Transaction Management API - an API to keep contracts clear and concise on transactions
It should be obvious, that writing a Transaction Management API is out of scope for most developers and only an adequately defined API can guarantee that applications remain flexible and adaptive.

The benefits of ORM's are too many for you not to have looked heavily into their proposed benefits.

In my next article, I'll present ways on how Spring provides a constructive and flexible programming model which addresses the concerns above and much more.


  1. của Nđồng tâm
    game mu
    cho thuê phòng trọ
    cho thuê phòng trọ
    nhac san cuc manh
    tư vấn pháp luật qua điện thoại
    văn phòng luật
    số điện thoại tư vấn luật
    dịch vụ thành lập doanh nghiệphạc Thành ở Thanh Dương môn đã là một cái tát lớn đối với Dịch gia, tất cả đều cho rằng đây là báo ứng của họ.

    Đối với kết quả này, người của Dịch gia cũng bất đắc dĩ vô cùng, tuy nhiên sự tình đã vậy bọn họ cũng vô phương phản hồi.

    Trong hoàng cung của Khoa Ốc đế quốc, ở nơi phồn hoa nhất, nơi này có diện tích rất lớn, kiến trúc trong đó cũng vô cùng xa xỉ san

    1. I am glad that I saw this post. It is informative blog for us and we need this type of blog thanks for share this blog, Keep posting such instructional blogs and I am looking forward for your future posts. Python Projects for Students Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account. Project Center in Chennai

  2. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Java Training in Chennai | Core Java Training in Chennai

    Online Java Training Java Online Training | Java J2EE Online Training | JavaEE Training Institute in Chennai

  3. Hibernate Training Institutes in ChennaiHibernate Training Institutes in Chennai Hibernate Online Training Hibernate Online Training Hibernate Training in Chennai Hibernate Training in Chennai Java Online Training Java Online Training

  4. I'm happy to read this article.Thanks for your information! Keep sharing..
    cloud erp in chennai

  5. It is not, at that point, a straightforward matter of making a twofold installment one month from now in addition to somewhat additional for charges, since the advances are not figured on typical loan fees. What really happens is more extreme than only a basic charge.

  6. Further, instead of holding up days or half a month for a choice, numerous online organizations will react inside a few hours. Rivalry in this market is savage, so they will do what it takes to get your business.

  7. The controls for vehicle title credits shift from state to state. In New Mexico, online loan specialists don't require that you live in the state. Auto Title Loans

  8. Your website content nice nice and interesting to observe.
    seo lüdenscheid

  9. This can differ from individual to individual contingent upon the conditions. Their cleverness can be put to use for training, home change, PC financing and some other individual need. Payday Loans Chula vista

  10. I hope to see more updates from you. Thank you for sharing.
    instagram search

  11. Extremely it’s an astonishing article I had ever read. I hope it will help significantly after all. Thanks for sharing. Keep it up.Customer Reconciliation
    Inventory Audit
    CFA Audit