Show Topics
Hide Topics

Spring Boot JDBC Example

Spring Boot provides starter and libraries for connecting to our application with JDBC. Spring JDBC dependencies can be resolved by using either spring-boot-starter-jdbc or spring-boot-starter-data-jpa spring boot starters.

 

 

1.Create project Structure

To create project go to https://start.spring.io/ and add JDBC,MySQL,JPA dependencies to the Project.

 

 

 

2.Configure DataSource (application. properties)

DataSource and Connection Pool are configured in application.properties file using prefix spring.datasource. Spring boot uses javax.sql.DataSource interface to configure DataSource

 

 

 3.Model Class(model.Student.java)

Find the MySQL table used in our example.

 

Create Student class with table properties

 

 

4.DAO Class with JdbcTemplate   (StudentDAO.java)

  • JdbcTemplate is the central class to handle JDBC. It executes SQL queries and fetches their results. To use JdbcTemplate.

 

  • JdbcTemplate dependency injection using @Autowired with constructor.
 

 

5.RowMapper Class

Spring JDBC provides RowMapper interface that is used to map row with a java object. We need to create our own class implementing RowMapper interface to map row with java object. Find the sample code to implement RowMapper interface.

 

 

SpringBootJdbcController.java

 

 

SpringBootApp.java

 

 

Static/index.jsp

 

 

Right click on Project> Run as> Java Application

 

 

We can discard RowMapper class if we write following code in StudentDAO class it self.

 

Download Example