Spring 在 JDBC 模板中使用具名参数

版权声明:博客知识产权来源命运的信徒,切勿侵权 https://blog.csdn.net/qq_37591637/article/details/85203970

Spring 的xml文件配置内容有

<!-- Spring使用模板具名参数 -->
<!-- 具名模板使用的话,必须是有参数的构造函数 -->
<bean id="namedparam" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="datasource"></constructor-arg>
</bean>

传统的方式是这样的

package cn.com.day03;
import java.util.HashMap;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
public class NamedTemplate {
//使用具名参数模板
private ApplicationContext ioc=null;
private NamedParameterJdbcTemplate namedParameterJdbcTemplate=null;
{
ioc=new ClassPathXmlApplicationContext("bean-jdbc.xml");	
namedParameterJdbcTemplate=ioc.getBean(NamedParameterJdbcTemplate.class);
}

public void testparam(){
String sql="insert into user values(:num,:name,:kind)";
Map<String,String> map=new HashMap<String,String>();
map.put("num", "7");
map.put("name", "桥本环奈");
map.put("kind", "演员");
namedParameterJdbcTemplate.update(sql, map);	
}
public static void main(String[] args) {
	NamedTemplate na=new NamedTemplate();
	na.testparam();
}
}

结果如下

但是这样的话,对于参数比较多的,添加多条数据的话,很不方便 ;


解决方案

//使用具名参数
public void paramTemplate(){
	String sql="insert into user"
             +" values(:number,:name,:kinds)";
	User u=new User("8", "苏麻喇姑", "侍女");
	SqlParameterSource paramSource=new BeanPropertySqlParameterSource(u);
	namedParameterJdbcTemplate.update(sql, paramSource);
}

前提是,这个:number :name :kinds的名字和User类名里面的属性名称要一致,不然会报错

Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter 'kind': Invalid property 'kind' of bean class [cn.com.day03.User]: Bean property 'kind' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
 

猜你喜欢

转载自blog.csdn.net/qq_37591637/article/details/85203970