【问题标题】:Spring JDBC with Spring Boot NullPointerException on NamedParameterJdbcTemplate在 NamedParameterJdbcTemplate 上带有 Spring Boot NullPointerException 的 Spring JDBC
【发布时间】: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


    【解决方案1】:

    我想通了。在我的调用函数中,我创建了一个 dao 的实例,而不是自动装配它。

    所以,我只需要改变

    UserDaoImpl userDao = new UserDaoImp();

    @Autowired
    UserDaoImpl userDao;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      相关资源
      最近更新 更多