根据项目的要求,我们希望在数据库处理中从JdbcTemplate更改为NamedParameterJdbcTemplate。但是当我测试我的编码时,我得到了零点错误。我确定由于我的配置而发生了错误,但我无法解决它。
配置
@Value("${spring.datasource.driver-class-name}")
protected String driver;
@Value("${spring.datasource.url}")
protected String url;
@Value("${spring.datasource.username}")
protected String user;
@Value("${spring.datasource.password}")
protected String pass;
@Bean
public DataSource dataSource(){
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(pass);
dataSource.setTestOnBorrow(true);
dataSource.setTestOnReturn(true);
dataSource.setTestWhileIdle(true);
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(){
return new JdbcTemplate(dataSource());
}
@Bean
public NamedParameterJdbcTemplate namedParameterJdbcTemplate(){
return new NamedParameterJdbcTemplate(dataSource);
}
DaoImpl
@Repository
public class DAOImpl implements DAO {
@Autowired
private NamedParameterJdbcTemplate jdbcTemplate;
@Override
public List<Type> findAllType() {
String sql = "select * from type";
RowMapper<Type> rm = new TypeRowMapper();
List<Type> list = jdbcTemplate.query(sql, rm);
return list;
}
}
测试
public class Test {
@Autowired
protected DAOImpl dao;
public static void main(String[] args) {
List<Type> list = new ArrayList<Type>();
Test test = new Test();
System.out.println(test.dao);
list = test.dao.findAllType();
for(Type type : list){
System.out.println(type.getName());
}
}
}
堆栈跟踪
空 线程&#34; main&#34;中的例外情况显示java.lang.NullPointerException 在com.example.dao.Test.main(Test.java:18)