Spring Framework Tutorial
Software Setup and Configuration (STS/Eclipse/IntelliJ)
Core Spring
Spring Annotations
Spring Data
Spring JDBC
Spring Security
In the Spring framework, the JdbcTemplate
is one of the most useful classes for working with databases. Under the hood, JdbcTemplate
uses JDBC's PreparedStatement
to execute queries. This helps in writing concise code and avoids many common errors associated with plain JDBC.
The use of PreparedStatement
has several advantages:
Here's a simple example to demonstrate how to use the JdbcTemplate
with prepared statements in Spring:
You'd need the following dependencies:
<!-- Spring JDBC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.10</version> </dependency> <!-- Database driver (e.g., H2 for demo purposes) --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.200</version> </dependency>
Here's a basic configuration for DataSource
and JdbcTemplate
:
@Configuration public class DatabaseConfig { @Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.h2.Driver"); dataSource.setUrl("jdbc:h2:mem:testdb"); dataSource.setUsername("sa"); dataSource.setPassword(""); return dataSource; } @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } }
Now, let's perform an insert operation using JdbcTemplate
:
@Repository public class UserDao { @Autowired private JdbcTemplate jdbcTemplate; public int addUser(String name, int age) { String sql = "INSERT INTO users (name, age) VALUES (?, ?)"; return jdbcTemplate.update(sql, name, age); } }
In the above code:
?
as placeholders. These placeholders are substituted with the parameters provided in the update
method.update
method is versatile and can be used for INSERT, UPDATE, and DELETE operations.This is a straightforward example of using JdbcTemplate
with a prepared statement. Remember to adjust configurations, methods, and table/column names to your specific application's requirements.
Using Prepared Statement in Spring JDBC Template:
Description:
The JdbcTemplate
in Spring allows the use of Prepared Statements for executing parameterized SQL queries. This helps prevent SQL injection and improves performance.
Code Example:
String sql = "SELECT * FROM employees WHERE department = ?"; jdbcTemplate.query(sql, new Object[]{"IT"}, new EmployeeRowMapper());
Configuring Prepared Statement queries in Spring:
Description:
Configuring Prepared Statement queries in Spring involves defining SQL queries with placeholders and passing parameter values at runtime using JdbcTemplate
.
Code Example:
String sql = "UPDATE products SET price = ? WHERE category = ?"; jdbcTemplate.update(sql, newPrice, "Electronics");
Parameterized queries with Prepared Statement in Spring:
Description: Parameterized queries with Prepared Statement in Spring involve using placeholders in SQL queries and supplying parameter values dynamically during execution.
Code Example:
String sql = "SELECT * FROM customers WHERE city = ?"; jdbcTemplate.query(sql, new Object[]{"New York"}, new CustomerRowMapper());
CRUD operations with Prepared Statement in Spring JDBC:
Description:
JdbcTemplate
supports CRUD operations with Prepared Statements. This includes executing parameterized insert, update, delete, and select queries.
Code Example:
// Insert operation String insertSql = "INSERT INTO products (name, price) VALUES (?, ?)"; jdbcTemplate.update(insertSql, "Laptop", 1200.0); // Update operation String updateSql = "UPDATE products SET price = ? WHERE id = ?"; jdbcTemplate.update(updateSql, 1300.0, 101); // Delete operation String deleteSql = "DELETE FROM products WHERE id = ?"; jdbcTemplate.update(deleteSql, 101);
Batch updates with Prepared Statement in Spring:
Description: Spring JDBC supports batch updates using Prepared Statements. This allows multiple SQL statements to be executed in a single batch.
Code Example:
String updateSql = "UPDATE products SET price = ? WHERE id = ?"; List<Object[]> batchArgs = Arrays.asList(new Object[]{50.0, 101}, new Object[]{45.0, 102}); jdbcTemplate.batchUpdate(updateSql, batchArgs);
Working with Prepared Statement in Spring MVC:
Description: In Spring MVC, working with Prepared Statements involves handling user input from forms and executing parameterized queries to interact with a database.
Code Example:
@PostMapping("/updateProduct") public String updateProduct(@RequestParam String name, @RequestParam double price) { String sql = "UPDATE products SET price = ? WHERE name = ?"; jdbcTemplate.update(sql, price, name); return "redirect:/products"; }
Dynamic SQL queries with Prepared Statement in Spring:
Description: Dynamic SQL queries with Prepared Statement in Spring involve building SQL queries based on runtime conditions, allowing flexibility in query generation.
Code Example:
StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM products WHERE 1=1"); List<Object> params = new ArrayList<>(); if (condition1) { sqlBuilder.append(" AND category = ?"); params.add("Electronics"); } if (condition2) { sqlBuilder.append(" AND price > ?"); params.add(50.0); } jdbcTemplate.query(sqlBuilder.toString(), params.toArray(), new ProductRowMapper());
Examples of Prepared Statement in Spring applications:
Description: Examples of using Prepared Statement in Spring applications cover scenarios such as querying, updating, and deleting records with dynamically provided parameters.
Code Example:
String sql = "SELECT * FROM employees WHERE department = ?"; jdbcTemplate.query(sql, new Object[]{"IT"}, new EmployeeRowMapper());