DataSource and JDBC Connection

Add below lines in build.gradle file :

	implementation 'mysql:mysql-connector-java:8.0.19'
	implementation 'org.springframework:spring-jdbc:3.2.0.RELEASE'

Bean file for MySQL db connection :

	@Autowired
	SimpleDriverDataSource ds;

	@Bean
	public JdbcTemplate jdbcTemplate() throws SQLException {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
		return jdbcTemplate;
	}
	
	@Bean
	public SimpleDriverDataSource getDriver() throws SQLException {
		SimpleDriverDataSource ds = new SimpleDriverDataSource();
		ds.setDriver(new com.mysql.cj.jdbc.Driver());
		ds.setUrl("jdbc:mysql://localhost:3306/mysql");
		ds.setUsername("tyson");
		ds.setPassword("tyson");
		return ds;
	}

Then you can use it any where using autowiring :

@Repository
public class EmpServiceDAO {
	
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	public List<Emp> getEmp() {
		List<Emp> empList = new ArrayList<>();
		String sql="select * from emp";
		Collection<Map<String,Object>> rows = jdbcTemplate.queryForList(sql);
		return new ArrayList<>();
	}
}

Data Source using XML file :

<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
   <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
   <property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
   <property name = "username" value = "root"/>
   <property name = "password" value = "admin"/>
</bean>

Using application.properties

 
# MySQL
#spring.datasource.url=jdbc:mysql://localhost:3306/test
#spring.datasource.username=dbuser
#spring.datasource.password=dbpass
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

Read More :

https://howtodoinjava.com/spring-boot2/datasource-configuration/

Leave a Comment