Reputation: 4287
I'm trying to following this guide to create a bean that gives me a DataSource Object, but when I try to access the Datasource, for example this way:
Connection connection = datasource.getConnection();
Statement stmt=connection.createStatement();
ResultSet rs=stmt.executeQuery("select * from products");
I get this error:
HikariPool-1 - dataSource or dataSourceClassName or jdbcUrl is required.
I edited my code many times, since I read various examples, that are always slightly different.
This is the last version of my code
@Configuration
@ComponentScan("com.packagename.webstore")
public class RootApplicationContextConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public HikariDataSource dataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
}
This is the application.properties file inside src/main/resources folder:
spring.datasource.jdbc-url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=password
spring.datasource.driverClassName=com.mysql.jdbc.Driver
This are my dependencies:
Does anybody understand what is my error?? Thank you
Upvotes: 4
Views: 20550
Reputation: 71
This should work for you.
# DataSource settings: Database configurations
spring.datasource.url = jdbc:mysql://localhost:3306/db_example
spring.datasource.username = springuser
spring.datasource.password = password
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
Have you try the Spring Data Repositories? If you use the Spring Data Repositories, you don't have to specify a Datasource object. If you want to implement repositories, you can follow this example:
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends CrudRepository<Product, Long> {
}
To call the service on a MVC @Service.
@Service
public class ProductService {
@Autowired
ProductRepository productRepository;
public List<Product> findAll() {
List<Product> results = null;
results = productRepository.findAll();
return results;
}
}
Upvotes: 3