Sunday, February 4, 2018

Data Source Set Up In Spring

In order to perform anything in a JDBC application, we need a connection object. In a traditional core java jdbc applications, we create the connection to a database using DriverManager, even though every application needs a connection object to work with a database, developer has to write this logic in every application (this kind of code is called boiler plate code). Instead of repeatedly writing it, spring has provided a declarative configuration for creating a connection. In this we declare the parameters that are required to create a connection object and spring would be able to automatically provide the connection to our code.

In order to get a connection, we need to configure DataSource in the configuration. A DataSource is a class which contains configuration information using which it creates connection object. A class which implements javax.sql.DataSource Interface can be configured as a DataSource spring bean. Spring provides one of the implementations of javax.sql.DataSource interface as part of its core package which is DriverManagerDataSource. This class is similar to DriverManager class in a traditional JDBC application. For this class we need to set the properties like DriverClass, Url, Username and Password for creating a connection. The sample configuration has been show in the below fragment.

persistence-beans.xml
<bean id=”dataSource”
         class=”org.springframework.jdbc.datasource.DriverManagerDataSource”>
         <property name=”url” value=”jdbc:oracle:thin:@//localhost:1521/xe”/>
         <property name=”username” value=”hr”/>
         <property name=”password” value=”hr”/>
         <property name=”driverClassName” value=”oracle.jdbc.driver.OracleDriver”/>
   </bean></pre>

The above dataSource bean is being injected into rest of the Spring Jdbc classes like JdbcTemplate or NamedParameterJdbcTemplate to execute Sql Operations.

Thanks for reading. If you like this post please follow us for more updates about technology related updates.

No comments: