1)JdbcTemplate
in Spring Framework
JdbcTemplate
is a core class provided by Spring JDBC for simplifying database access. It handles the creation and release of resources, and provides methods for executing SQL queries, updates, and stored procedures, as well as for mapping ResultSets to objects.
🔷 Why use JdbcTemplate
?
-
✅ Eliminates boilerplate code (e.g., connection handling, statement closing).
-
✅ Integrates seamlessly with Spring's transaction management.
-
✅ Helps in writing cleaner, maintainable, and testable code.
-
✅ Provides callback interfaces (like
RowMapper
,ResultSetExtractor
) for custom result mapping.
🔷 Common Methods in JdbcTemplate
Method | Description |
---|---|
query() | Runs a SELECT query and maps each row using a RowMapper . |
queryForObject() | Runs a SELECT query expecting a single result. |
queryForList() | Returns a list of rows (each row as a Map or a simple object). |
update() | Executes INSERT, UPDATE, DELETE statements. |
batchUpdate() | Executes batch updates. |
execute() | Runs general SQL (e.g., DDL statements). |
🔷 Basic Setup
✅ 1. Maven Dependency
xml<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.30</version>
</dependency>
✅ 2. Configuration Example
@Configuration
public class AppConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/mydb");
ds.setUsername("root");
ds.setPassword("password");
return ds;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
🔷 Example Usage
✅ Insert Data
@Autowired
private JdbcTemplate jdbcTemplate;
public int saveEmployee(String name, double salary) {
String sql = "INSERT INTO employee(name, salary) VALUES (?, ?)";
return jdbcTemplate.update(sql, name, salary);
}
✅ Fetch Single Record
public Employee getEmployeeById(int id) {
String sql = "SELECT * FROM employee WHERE id = ?";
return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Employee.class), id);
}
✅ Fetch Multiple Records
public List<Employee> getAllEmployees() {
String sql = "SELECT * FROM employee";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Employee.class));
}
✅ Custom RowMapper
public class EmployeeRowMapper implements RowMapper<Employee> {
@Override
public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
Employee emp = new Employee();
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
emp.setSalary(rs.getDouble("salary"));
return emp;
}
}
public List<Employee> getEmployees() {
String sql = "SELECT * FROM employee";
return jdbcTemplate.query(sql, new EmployeeRowMapper());
}
🔷 Best Practices
-
Use named parameters with
NamedParameterJdbcTemplate
for clarity. -
Avoid using
*
in queries — select explicit columns. -
Use
RowMapper
orBeanPropertyRowMapper
for object mapping. -
Integrate with Spring Transaction management (
@Transactional
).
🔷 Real-World Use Case
@Repository
public class EmployeeRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<Employee> findEmployeesByDept(String dept) {
String sql = "SELECT * FROM employee WHERE department = ?";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Employee.class), dept);
}
public int updateSalary(int empId, double salary) {
String sql = "UPDATE employee SET salary = ? WHERE id = ?";
return jdbcTemplate.update(sql, salary, empId);
}
}
2.
HibernateTemplate
in SpringFrameWork
HibernateTemplate
is a helper class provided by the Spring Framework (part of org.springframework.orm.hibernate5
) that simplifies data access code using Hibernate. It follows the Template Method design pattern and handles repetitive boilerplate code such as opening/closing sessions, handling transactions, and translating exceptions.
It is typically used in Spring + Hibernate integration to simplify DAO (Data Access Object) operations.
🔷 Core Benefits of HibernateTemplate
with Detailed Explanation and Examples
✅ 1. Simplifies Interactions with Hibernate Session
Hibernate operations like save
, update
, delete
, and get
require boilerplate code using Session
, Transaction
, and proper try-catch-finally blocks. HibernateTemplate
encapsulates all that internally.
🔸 Example Without HibernateTemplate
:
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(emp);
tx.commit();
} catch (Exception e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
🔸 Example With HibernateTemplate
:
private HibernateTemplate hibernateTemplate;
public void saveEmployee(Employee emp) {
hibernateTemplate.save(emp);
}
🔹 Benefit: Just one line replaces multiple lines of session, transaction, and exception-handling code.
✅ 2. Common Functions Are Simplified to Single Method Calls
HibernateTemplate provides convenient one-liner methods for common database operations.
🔸 Example: Load all Employees
✅ 3. Automatic Session Management
You don’t need to manually manage Session
objects. It internally opens, flushes, and closes the session, so you avoid common mistakes like session leaks or forgetting to close.
✅ 4. Automatic Exception Translation
Hibernate throws checked exceptions like HibernateException
. HibernateTemplate
converts these into Spring’s runtime DataAccessException
, which is part of a unified exception hierarchy in Spring.
This means:
No need to catch or declare checked exceptions.
Exception handling becomes easier and consistent across the DAO layer.
🔸 Example:
hibernateTemplate.save(emp);
} catch (DataAccessException ex) {
// Handle exception without worrying about checked HibernateException
}
✅ 5. Integration with Spring Transactions
HibernateTemplate
works well with Spring’s @Transactional
annotation. You can define transaction boundaries declaratively at the service layer.
🔸 Example:
public void updateEmployee(Employee emp) {
hibernateTemplate.update(emp);
}
This ensures:
Automatic rollback on exceptions.
Commit if no exception is thrown.
✅ 6. Support for Callback Programming (HibernateCallback
)
For complex queries or operations, you can pass a custom implementation of HibernateCallback
to execute()
method, gaining full access to Session
object.
🔸 Example:
session.createQuery("from Employee where salary > 50000", Employee.class).list()
);
🔹 Benefit: You still get session and exception management while using advanced features.
✅ 7. Clean and Readable DAO Code
By abstracting away boilerplate, HibernateTemplate
allows you to write clean, concise, and maintainable DAO classes.
✅ Summary Table: Benefits of HibernateTemplate
⚠️ Note on Modern Usage
HibernateTemplate
was widely used with Hibernate 3 and 4.
In modern Spring Boot applications, it's largely replaced by Spring Data JPA (JpaRepository
), which offers even more abstraction.
However, HibernateTemplate
is still relevant in legacy systems and for understanding underlying data access design patterns.
public void saveEmployee(Employee emp) {
@Autowired
Operation HibernateTemplate Method Save save(Object entity)
Update update(Object entity)
Delete delete(Object entity)
Retrieve get(Class, Serializable)
List All loadAll(Class)
java
List<Employee> employees = hibernateTemplate.loadAll(Employee.class);
try {
@Transactional
javaList<Employee> result = hibernateTemplate.execute(session ->
Benefit Explanation Simplified Hibernate interaction One-liner for common operations like save, get, update Automatic session management No need to manually open/close sessions Auto exception translation Converts Hibernate exceptions to Spring's DataAccessException Integrated with Spring AOP Works with @Transactional
Callback support Allows advanced queries with HibernateCallback
Encourages best practices Cleaner, safer, and reusable code patterns
🟩 3) MongoTemplate
in Java (Spring Data MongoDB)
MongoTemplate
is a core class in Spring Data MongoDB used to interact with MongoDB. It provides a powerful and flexible way to perform CRUD operations, aggregation, indexing, and more.
🔷 Why use MongoTemplate
?
✅ Direct control over MongoDB queries
✅ Fine-grained operations (complex queries, custom conversions)
✅ Integrates with Spring’s dependency injection
✅ Supports aggregation framework
✅ Better for advanced use-cases than repository interfaces
🔷 Maven Dependency
Add this to your pom.xml
:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
🔷 Configuration
Spring Boot auto-configures MongoTemplate
using application.properties
:
properties
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=testdb
Or customize using a MongoClient
bean:
@Configuration
public class MongoConfig {
@Bean
public MongoClient mongoClient() {
return MongoClients.create("mongodb://localhost:27017");
}
@Bean
public MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient(), "testdb");
}
}
🔷 Entity Class Example
@Document(collection = "employees")
public class Employee {
@Id
private String id;
private String name;
private String department;
private double salary;
// Getters & setters
}
🔷 Basic Operations with MongoTemplate
Assume we autowire MongoTemplate
:
@Autowired
private MongoTemplate mongoTemplate;
✅ Insert a Document
public void insertEmployee(Employee emp) {
mongoTemplate.insert(emp);
}
✅ Find All Documents
public List<Employee> findAllEmployees() {
return mongoTemplate.findAll(Employee.class);
}
✅ Find by Field
public List<Employee> findByDepartment(String dept) {
Query query = new Query();
query.addCriteria(Criteria.where("department").is(dept));
return mongoTemplate.find(query, Employee.class);
}
✅ Find by ID
public Employee getById(String id) {
return mongoTemplate.findById(id, Employee.class);
}
✅ Update Document
public void updateSalary(String id, double newSalary) {
Query query = new Query(Criteria.where("id").is(id));
Update update = new Update().set("salary", newSalary);
mongoTemplate.updateFirst(query, update, Employee.class);
}
✅ Delete Document
public void deleteById(String id) {
Query query = new Query(Criteria.where("id").is(id));
mongoTemplate.remove(query, Employee.class);
}
✅ Aggregation Example
public List<Document> getAvgSalaryByDept() {
Aggregation agg = Aggregation.newAggregation(
Aggregation.group("department").avg("salary").as("avgSalary")
);
AggregationResults<Document> results = mongoTemplate.aggregate(agg, "employees", Document.class);
return results.getMappedResults();
}
🔷 Summary of Key Classes
Class Purpose MongoTemplate
Main class for interacting with MongoDB Query
Defines search conditions Criteria
Defines field conditions (e.g., .where("field").is(value)
) Update
Used for specifying update operations Aggregation
Used to build MongoDB aggregation pipelines @Document
Annotation to define MongoDB collection mapping @Id
Marks the primary identifier of a document
🔷 When to Use MongoTemplate
vs MongoRepository
Use Case Tool Simple CRUD MongoRepository
Complex Queries MongoTemplate
Aggregation Pipelines MongoTemplate
Fine-grained control MongoTemplate
No comments:
Post a Comment