【发布时间】:2021-12-14 18:04:00
【问题描述】:
我使用 Spring Boot 和 Spring JDBC 编写了一个程序。出于某种原因,我在NamedParameterJdbcTemplate 上收到了NullPointerException。
DAOImpl:
@Repository
@Transactional
public class UserDaoImpl implements UserDao {
private NamedParameterJdbcTemplate jdbcTemplate;
private static final TABLE_NAME = "users";
@Autowired
private void setjdbcTemplate(NamedParameterJdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
@Transactional(readOnly = true)
public User getUser(String userName) {
String userQuery = "SELECT * FROM " + TABLE_NAME + " WHERE user_name LIKE :username";
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("username", userName);
return jdbcTemplate.queryForObject(userQuery, parameterSource, new userRowMapper());
}
}
application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/testing_schema
spring.datasource.username=****
spring.datasource.password=****
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
据我从Spring documentation 得知,这应该足够了。此外,this question 的答案解释说,一切都应该为我创建,我只需要自动装配。但是,我无法弄清楚为什么它仍然返回 null。如有任何帮助,我将不胜感激。
【问题讨论】:
标签: mysql spring-boot gradle spring-jdbc