Spring持久层(二)Spring 命名JdbcTemplate 的例子

    技术2022-05-19  20

    首先Spring in action例子有个bug

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

    运行程序,出现错误打印

    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'namedParameterJdbcTemplate' defined in URL [file:src/test-context.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.<init>()

     

    需要修改为

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

     

    参考Spring持久层(一)

    修改之处

    1 配置文件,添加bean定义

    <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <constructor-arg ref="dataSource" /> </bean> <bean id="namedParameterProductDao" class="springapp.repository.NamedParameterJdbcTemplateProductDao"> <property name="jdbcTemplate" ref="namedParameterJdbcTemplate"></property> </bean>

     

    2 NamedParameterJdbcTemplateProductDao.java源码

    public class NamedParameterJdbcTemplateProductDao implements ProductDao { private NamedParameterJdbcTemplate jdbcTemplate; public void setJdbcTemplate(NamedParameterJdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public List<Product> getProductList() { // TODO Auto-generated method stub return null; } @Override public void saveProduct(Product prod) { String sql = "insert into products (id, price, description) values (:id, :price, description)"; Map para = new HashMap(); para.put("id", prod.getId()); para.put("price", prod.getPrice()); para.put("description", prod.getDescription()); jdbcTemplate.update(sql, para); } }

     

    3 测试代码

    public class NamedParameterJdbcTemplateProductDaoTest { static ApplicationContext ctx = new ClassPathXmlApplicationContext( new String[] { "file:src/test-context.xml" }); public static void main(String[] args) { ProductDao dao = (ProductDao) ctx.getBean("productDao"); Product product = new Product(); product.setId(2); product.setPrice(12.2); product.setDescription("description1"); dao.saveProduct(product); } }


    最新回复(0)