Hobbies
Hobbies
Transaction Management:
Spring Boot supports declarative transaction management using @Transactional. This
allows you to manage database transactions easily without manually handling
commit/rollback operations.
Example:
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserService {
@Transactional
public void addUser(String name, int age) {
String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
jdbcTemplate.update(sql, name, age);
}
}
4. Customizing DataSource:
If you need to configure a custom DataSource, you can do it manually by creating a
configuration class and providing your own database settings.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
@Configuration
public class DatabaseConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/mydatabase");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
}
Advantages of Using JDBC in Spring Boot:
Ease of Configuration: Spring Boot simplifies database setup with auto-
configuration, eliminating the need for complex configurations in web.xml or
applicationContext.xml.
Declarative Transaction Management: You can use @Transactional for transaction
management, making it easy to control commits and rollbacks.
JdbcTemplate: Spring Boot's JdbcTemplate provides an easier way to interact with
the database compared to raw JDBC, reducing boilerplate code.
Integration with Spring Data JPA: For more complex applications, you can use Spring
Data JPA to further abstract database operations and leverage an ORM for object-
relational mapping.
Summary:
JDBC is a Java API for connecting to databases and executing SQL queries.
Spring Boot uses JDBC to interact with databases through auto-configuration,
JdbcTemplate, and simple database setup.
It simplifies database connectivity and management, reducing the need for manual
configuration and boilerplate code.
Spring Boot provides a high-level abstraction over raw JDBC operations, making it
easier to integrate with databases in Java-based web applications.