Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify DataSource in JdbcTemplate?

Tags:

spring-boot

In my application.properties I have set:

datasource.test.driverClass=org.postgresql.Driver
datasource.test.url=jdbc:postgresql://localhost:5433/test
datasource.test.username=admin
datasource.test.password=admin

logging.level.com.eternity = DEBUG

In my controller, I am trying to execute some SQL query form a string like this:

String selectQueryPartOne = "SELECT name, ("+ StringUtils.join(sumString, " + ")+") AS 'Price' FROM house WHERE NOT (" +StringUtils.join(sumString, " IS NULL OR ")+" IS NULL);";
JdbcTemplate statement = new JdbcTemplate();
statement.queryForList(selectQueryPartOne);

Which would work fine, however, I am receiving the following error:

java.lang.IllegalArgumentException: No DataSource specified

I've discovered, that in my statement object, I need to setDataSource first. However, I have no idea where I can get this dataSource object. Could you help?

like image 435
uksz Avatar asked Oct 18 '25 14:10

uksz


1 Answers

When you create the JdbcTemplate instance yourself, you are working outside of the Spring dependency injection, and therefore will not have the DataSource injected. You need to use the Spring-provided instance via autowiring, something like:

@Controller
public class MyController {
    @Autowired private JdbcTemplate jdbcTemplate;

    @RequestMapping("/")
    public String myAction(){
        // do stuff with the jdbc template
    }
}

Also, the Spring and Spring-boot documentation are great resources for further study on working with spring.

like image 131
cjstehno Avatar answered Oct 20 '25 06:10

cjstehno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!