Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

CHAPTER 1: An Introduction to Hibernate ... > Origins of Hibernate and Object-Rela...

Origins of Hibernate and Object-Relational Mapping

If Hibernate is the solution, what was the problem? One answer is that doing things the right way when using JDBC requires a considerable body of code, and careful observation of various rules (such as those governing connection management) to ensure that your application does not leak resources. The gargantuan body of code in Listing 1-3 is required to populate the example Motd object from the database even when you know the appropriate message identifier.

Listing 1-3. The JDBC Approach to Retrieving the POJO

   public static List getMessages(int messageId) throws MessageException {
      Connection c = null;
      PreparedStatement p = null;
      List list = new ArrayList();

      try {

         Class.forName("org.postgresql.Driver");
         c = DriverManager.getConnection(
               "jdbc:hsqldb:testdb;shutdown=true",
               "hibernate",
               "hibernate");
         p = c.prepareStatement(
               "select message from motd");

         ResultSet rs = p.executeQuery();

         while(rs.next()) {
            String text = rs.getString(1);
            list.add(new Message(text));
         }
         return list;
         } catch (Exception e) {
            log.log(Level.SEVERE, "Could not acquire message", e);
            throw new MotdException(
                  "Failed to retrieve message from the database.", e);
         } finally {
            if (p != null) {
               try {
                  p.close();
               } catch (SQLException e) {
                  log.log(Level.WARNING,
                        "Could not close ostensibly open statement.", e);
               }
           }

           if (c != null) {
              try {
                 c.close();
              } catch (SQLException e) {
                 log.log(Level.WARNING,
                       "Could not close ostensibly open connection.", e);
              }
          }
      }
   }

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint