Using JdbcTemplate

We will use a similar outline of the project used in Ch03_DataSourceConfiguration, and redevelop it with the help of the following steps:

  1. Create a new Java application named Ch03_JdbcTemplate, and add jar, which we used in Ch03_DataSourceIntegration. Along with it, add spring-tx-5.0.0.RC1.jar as well.
  2. Create or copy Book in the com.packt.ch03.beans package.
  3. Create or copy BookDAO in the com.packt.ch03.dao package.
  4. Create BookDAOImpl_JdbcTemplate in the com.packt.ch03.dao package, and add to it JdbcTemplate as a data member.
  5. Annotate the class with @Repository, and the JdbcTemplate data member with the @Autowired annotation, respectively.
  6. The overridden methods will deal with insertion of Book in the table. However, we don't have to get the connection. Also, we will not do creation and setting of parameters of PreparedStatement. The JdbcTemplate will do it for us. Things will be pretty clear from the following code:
        @Repository(value = "bookDAO_jdbcTemplate") 
        public class BookDAO_JdbcTemplate implements BookDAO { 
           @Autowired 
          JdbcTemplate jdbcTemplate; 
 
          @Override 
          public int addBook(Book book) { 
            // TODO Auto-generated method stub 
            int rows = 0; 
            String INSERT_BOOK = "insert into book  
            values(?,?,?,?,?,?)"; 
          rows=jdbcTemplate.update(INSERT_BOOK, book.getBookName(),     
          book.getISBN(), book.getPublication(),   
          book.getPrice(),book.getDescription(),  
          book.getAuthor()); 
          return rows; 
          } 
        } 

JdbcTemplate has an update() method, where the developers need to pass the SQL query followed by the values of the parameters in the query. So, we can use it for insertion and updation, as well as deletion of data. All the rest will be done by the template. If you keenly observe, we are not handling any exceptions. Did we forget to do so? No, we don't care to handle them, as Spring provides DataAccessException, which is an unchecked exception. So leave the worries. In the upcoming pages, we will discuss the exceptions that Spring provides.

Let's add a method in the code to update the book's price as well as to delete the book. Don't forget to change the interface implementation first. The code is shown as follows:

        @Override 
        public int updateBook(longISBN, intprice) { 
          // TODO Auto-generated method stub 
          int rows = 0; 
          String UPDATE_BOOK = "update book set price=? where  
          ISBN=?"; 
          rows=jdbcTemplate.update(UPDATE_BOOK, price,ISBN); 
          return rows; 
         } 
 
        @Override 
        public boolean deleteBook(longISBN) { 
          // TODO Auto-generated method stub 
          int rows = 0; 
          boolean flag=false; 
          String DELETE_BOOK = "delete from book where ISBN=?"; 
          rows=jdbcTemplate.update(DELETE_BOOK, ISBN); 
          if(rows>0) 
          flag=true; 
          return flag; 
        } 
  1. Let's add the beans configuration file as connection_new.xml. You can simply copy it from the Ch03_DataSourceIntegration project. We are using the JdbcTemplate that has DataSource as its dependency. So, we will need to configure two beans--one for DataSource, and another for JdbcTemplate, shown as follows:
        <context:annotation-config/> 
        <context:component-scan base- 
          package="com.packt.ch03.*">
</context:component-scan> <bean id="dataSource" class="org.springframework.jdbc.datasource
.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/bookDB"/> <property name="username" value="root"/> <property name="password" value="mysql"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource">
</property> </bean>
  1. Write the following code to get the bookDAO_jdbcTemplate bean, and execute the operations in MainBookDAO_operations:
        public class MainBookDAO_operations { 
           public static void main(String[] args) { 
              // TODO Auto-generated method stub 
              ApplicationContext context=new 
                ClassPathXmlApplicationContext("connection_new.xml"); 
              BookDAO bookDAO=(BookDAO)  
                context.getBean("bookDAO_jdbcTemplate"); 
              //add book 
              introws=bookDAO.addBook(new Book("Java EE 7 Developer  
              Handbook", 97815674L,"PacktPub  
                publication",332,"explore the Java EE7  
                programming","Peter pilgrim")); 
              if(rows>0) 
              { 
                System.out.println("book inserted successfully"); 
              }   
              else 
                System.out.println("SORRY!cannot add book"); 
              //update the book 
              rows=bookDAO.updateBook(97815674L,432); 
              if(rows>0) 
              { 
                System.out.println("book updated successfully"); 
              } 
              else 
              System.out.println("SORRY!cannot update book"); 
              //delete the book 
              boolean deleted=bookDAO.deleteBook(97815674L); 
              if(deleted) 
              { 
                System.out.println("book deleted successfully"); 
              } 
              else 
                System.out.println("SORRY!cannot delete book"); 
            } 
        } 
  1. What are you waiting for? Just execute the code, and get the statements denoting insertion, updation, and deletion of the book on the console.
Configure a single bean for JdbcTemplate, and use it for insertion to multiple DAOs, as once configured, the instance of the JdbcTemplate class is thread safe.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.36.30