Case 1 - Using XML configuration of DriverManagerDataSource

  1. Create a Core Java application named Ch03_DataSourceConfiguration, and add to it the jar for Spring and JDBC, as shown in the outline of the following application:
  1. Create a Book POJO in the com.ch03.packt.beans package, as shown in the following piece of code:
        public class Book { 
          private String bookName; 
          private long ISBN; 
          private String publication; 
          private int price; 
          private String description; 
          private String [] authors; 
 
          public Book() { 
            // TODO Auto-generated constructor stub 
            this.bookName="Book Name"; 
            this.ISBN =98564567l; 
            this.publication="Packt Publication"; 
            this.price=200; 
            this.description="this is book in general"; 
            this.author="ABCD"; 
          } 
 
          public Book(String bookName, long ISBN, String 
          publication,int price,String description,String 
            author)  
          { 
            this.bookName=bookName; 
            this.ISBN =ISBN; 
            this.publication=publication; 
            this.price=price; 
            this.description=description; 
            this.author=author; 
          } 
          // getters and setters 
          @Override 
          public String toString() { 
            // TODO Auto-generated method stub 
            return bookName+"	"+description+"	"+price; 
          } 
        } 
  1. Declare a BookDAO interface in the com.ch03.packt.dao package.
  2. Add to it a method for adding a book to the database. The code will be as follows:
        interface BookDAO 
        { 
          public int addBook(Bookbook); 
        } 
  1. Create an implementation class for BookDAO as BookDAOImpl, and add a data member of type DataSource in the class, as shown in the following line of code:
        private DataSource dataSource; 

Don't forget to use the standard bean naming conventions.

  1. As we are following setter injection, write or generate setters for DataSource.
  2. The overridden method will deal with getting the connection from DataSource and using PreaparedStatement to insert a book object in the table, as we do in JDBC. This is shown in the following piece of code:
        public class BookDAOImpl implements BookDAO { 
          private DataSource dataSource; 
 
          public void setDataSource(DataSource dataSource) { 
            this.dataSource = dataSource; 
          } 
 
          @Override 
          public int addBook(Book book) { 
          // TODO Auto-generated method stub 
          int rows=0; 
          String INSERT_BOOK="insert into book values(?,?,?,?,?,?)"; 
          try { 
            Connection connection=dataSource.getConnection(); 
            PreparedStatement ps=  
              connection.prepareStatement(INSERT_BOOK); 
            ps.setString(1,book.getBookName()); 
            ps.setLong(2,book.getISBN()); 
            ps.setString(3,book.getPublication()); 
            ps.setInt(4,book.getPrice()); 
            ps.setString(5,book.getDescription()); 
            ps.setString(6,book.getAuthor()); 
            rows=ps.executeUpdate(); 
          } catch (SQLException e) { 
              // TODO Auto-generated catch block 
              e.printStackTrace(); 
            } 
            return rows; 
          }
        } 
  1. Create connection.xml in the classpath to configure the beans.
  2. Now, the question is, how many beans are to be declared and what are their ID's?
A very simple thumb rule: First, find out the class to configure, and then, what are its dependencies.

Here we need beans for the following:

  • A bean for BookDAOImpl
  • BookDAOImpl has DataSource as a dependency, so a bean for DataSource

You will be wondering that DataSource is an interface! So, how can we create and inject its object? Yes, this is our point! This is what we are talking about; loosely coupled modules. The DataSource implementation, which we are using here, is DriverManagerDataSource. However, if we directly inject DriverManagerDataSource, then the class will be tightly coupled on it. Also, if tomorrow, instead of using DriverManagerDataSource the team decides to use some other implementation, then the code has to be changed, which leads to recompilation and redeployment. That means the better solution is to use an interface, and inject its implementation from the configuration.

The id can be of developer's choice, but don't neglect to take advantage of autowiring, and then, accordingly set the id. Here, we will use autowiring byName, so choose the id accordingly. byName is one of the autowiring strategies that provides information to the Spring container. It tells the container to auto-discover the nonconfigured dependency by its name. As we've already covered annotation-based autowiring in the preceding chapter, here we will use XML-based autowiring using the autowire attribute while configuring the bean. You can even go for annotation-based configuration (if you are confused, or want to dig about autowiring using annotation, you can refer to the previous chapter for how to resolve ambiguity using the @Qualifier annotation). So, the final configuration in XML is as follows:

<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="bookDao"class="com.packt.ch03.dao.BookDAOImpl" 
  autowire="byname"> 
</bean> 

You may need to customize the URL, username, and password to match your connection parameters. Observe the attribute 'autowire' configured for the bookDao bean. Instead of using @Qualifier to resolve the ambiguity, we used the value of the attribute as byName here:

  1. Normally, the DAO layer will be invoked by the Service layer, but here, we are not dealing with it; we will add it as the application proceeds. As we have not yet discussed testing, we will write a code with the main function to find its output. The main function will get the BookDAO bean, and invoke a method on it to insert the book. If the value of the row returned by the implementation code is greater than zero, the book got successfully added, otherwise not. Create a MainBookDAO class, and add the following code to it:
        public static void main(String[] args) { 
          // TODO Auto-generated method stub 
          ApplicationContext context=new 
            ClassPathXmlApplicationContext("connection.xml"); 
          BookDAO bookDAO=(BookDAO) context.getBean("bookDao"); 
          introws=bookDAO.addBook(new Book("Learning Modular  
            Java Programming", 9781234,"PacktPub  
            publication",800,"explore the power of  
            Modular programming","T.M.Jog")); 
          if(rows>0) 
          { 
            System.out.println("book inserted successfully"); 
          } 
          else 
          System.out.println("SORRY!cannot add book"); 
        } 

If you observed keenly, though we configure an object of BookDAOImpl, we are accepting it in the BookDAO interface, which helps you in writing flexible code, where the main code is actually unaware of whose object is giving the implementation.

  1. Open your MySQL console, and use credentials to log in. Fire a query to create a BookDB schema and a Book table, shown as follows:
  1. Now, you are all set to execute the code to get book inserted successfully on the console. You can fire select * from book in MySQL to get the book details as well.
..................Content has been hidden....................

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