Spring jdbc 空指针异常
来源:1-5 自由编程
weixin_慕仙7241916
2022-09-13 16:45:30
尝试了几次还是找不出原因,请老师协助
DB的部份查询同样的语句是没问题的,但Java的步骤出现空指针异常,请问老师要如何解决?


debug mode

Service类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class HotelServiceTest extends TestCase {
@Resource
private HotelDao hotelDao;
@Test
public void testFindById(){
Hotel hotel = hotelDao.findById(10001);
System.out.println(hotel);
}
}DAO类
@Repository
public class HotelDao {
private JdbcTemplate jdbcTemplate;
@Resource
private Hotel hotel;
public Hotel findById(Integer oid){
String sql = "SELECT * FROM hotel WHERE orderno = ?";
Hotel hotel = jdbcTemplate.queryForObject(sql, new Object[]{oid}, new BeanPropertyRowMapper<Hotel>(Hotel.class));
return hotel;
}
}1回答
同学你好,1、空指针异常是因null调用方法导致的问题。如下所示:

2、建议同学注入JdbcTemplate。如下所示:然后重新测试代码试一下。
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean>
祝学习愉快!
相似问题