JdbcTemplate: A Step-by-Step Guide to Fetching Single Entity Objects in Java
- Introduction :
In Java programming, working with databases is a common task. The JdbcTemplate class in the Spring Framework simplifies database operations by providing a convenient way to interact with relational databases. One common scenario is retrieving a single entity object from the database using JdbcTemplate. - JdbcTemplate :
JdbcTemplate is a powerful utility class provided by the Spring Framework that eliminates the need for boilerplate code when working with databases. - Retrieving a Single Entity Object :
Now, let’s focus on the main objective of this article: retrieving a single entity object using JdbcTemplate in Java. We will walk through the necessary steps in a clear and concise manner.
- Configure the Data Source
To use JdbcTemplate, you need to configure the data source for your database. This can be done in the application configuration file. You can find here for configuration details.
A Step-by-Step Tutorial For Creating Spring Boot Application
spring.datasource.url=jdbc:mysql://localhost:3306/book_store spring.datasource.username=root spring.datasource.password=root #Basic Drivers for connecting with database spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.EJB3NamingStrategy spring.datasource.testOnBorrow=true spring.datasource.validationQuery=SELECT 1 spring.jpa.hibernate.ddl-auto=update spring.jpa.database=mysql server.port=9080
- Create a DAO Class
Next, you need to create a Data Access Object (DAO) class that will be responsible for executing database queries and mapping the results to Java objects. The DAO class serves as an intermediary between your application and the database. You can use service Implementation class as well. - Define a SQL Query
In this step, you define the SQL query that retrieves the desired entity object from the database. The query should include the necessary conditions, such as the primary key, to ensure you retrieve the correct object. JdbcTemplate supports both named parameters and positional parameters, providing flexibility in parameterization. - Execute the Query
Using JdbcTemplate, you execute the SQL query defined in the previous step. JdbcTemplate takes care of establishing the database connection, executing the query, and handling any exceptions that may occur. The result of the query execution is a ResultSet object containing the retrieved data. - Map the Result to the Entity Object
To convert the ResultSet object into a Java object, you need to map each column value to the corresponding attribute in the entity class. JdbcTemplate provides various ways to achieve this mapping, including RowMapper interfaces and lambda expressions. By implementing the appropriate mapping, you can create an instance of the entity object and populate its attributes with the retrieved data. - Return the Entity Object
Finally, you return the entity object from the DAO class, making it available for further processing in your application. - Finally here code will looks like
@GetMapping(value = "/readBookUsingJdbc/{authorId}") public Object readBookUsingJdbc(@PathVariable(name = "authorId") Long authorId) { return bookService.readBookUsingJdbc(authorId); }
public Object readBookUsingJdbc(Long authorId) { log.debug("Method called to Read all book using Jdbc"); String sqlQuery ="select * from book where author_id =?"; @SuppressWarnings("deprecation") Book object = (Book) this.jdbcTemplate.queryForObject( sqlQuery, new Object[]{authorId}, new RowMapper<Book>() { public Book mapRow(ResultSet rs, int rowNum) throws SQLException { Book object = new Book(); object.setId(rs.getLong("id")); object.setCode(rs.getString("code")); object.setDescription(rs.getString("description")); object.setName(rs.getString("name")); return object; } }); return object; }
Result after hitting api
There is another approach to get the same data
public Object readBookUsingJdbc(Long authorId) { log.debug("Method called to Read all book using Jdbc"); String sqlQuery ="select * from book where author_id ="+authorId; List<Book> books = jdbcTemplate.query(sqlQuery,(rs, rowNum) -> new Book(rs.getLong("id"), rs.getString("code"),rs.getString("name"),rs.getString("description"))); return books.get(0); }
A Step-by-Step Tutorial For Creating Spring Boot Application
Building Spring Boot Rest Api in Java
Java Hibernate Magic: Create MySQL Tables with Ease and Efficiency
One Reply to “JdbcTemplate: A Step-by-Step Guide to Fetching Single Entity Objects in Java”