Java spring自动装配Jdbctemplate但不是NamedParameterJdbcTemplate

时间:2016-04-13 09:56:46

标签: java spring-mvc spring-jdbc

我有使用Jdbc进行sql-access的东西。我可以使用JdbcTemplate但不能使用NamedParameterJdbcTemplate。 namedparam总是返回空指针,而jdbctemplate就像魅力一样。我正在使用spring 4.2.4.RELEASE

我在这里错过了一步吗?这是简化代码:

弹簧data.xml中:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath*:/db_connection.properties" />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${db.driver}" />
        <property name="url" value="${db.url}" />
        <property name="username" value="${db.username}" />
        <property name="password" value="${db.password}" />
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <constructor-arg ref="dataSource" />
    </bean>

</beans>

someDAOImpl.java:

/* 
    imports
*/

@Component
public class someDAOImpl implements someDAO {

    @Autowired
        private JdbcTemplate jdbcTemplate;
        private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public void thisDoesntWork(Integer intValue) {
        String sql = "UPDATE table SET value = :value WHERE id = 1";
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("value", intValue);
        try {
            namedParameterJdbcTemplate.update(sql, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ArrayList<ResultClass> thisWorks(Integer intValue) {

        String sql = "SELECT * FROM table WHERE value = ?";
        ArrayList<ResultClass> results = new ArrayList<ResultClass>();
        try {
            results = (ArrayList<ResultClass>) jdbcTemplate.query(sql, new Object[] { intValue }, new ResultClassMapper());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return results; 
    }
}

1 个答案:

答案 0 :(得分:1)

您还需要自动装配namedParameterJdbcTemplate

@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;