1.SpringJdbc的使用以及namedTemplate的使用
<!--注入springTemplate>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="springTemplate" class="service.SpringTemplate" autowire="byName">
</bean>
<!--继承JdbcDaoSupport,使用getJdbcTemplate()即可获取到对象>
<bean id="jdbcDaoSupportImpl" class="service.JdbcDaoSupportImpl">
<property name="dataSource" ref="dataSource" />
<property name="namedTemplate" ref="namedTemplate"/>
</bean>
<!--namedTemplate直接注入即可,namedTemplate bean配置如下-->
<bean id="namedTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" abstract="false" lazy-init="false" autowire="default" >
<constructor-arg type="javax.sql.DataSource" ref="dataSource" />
</bean>
2.增删改相关操作
使用update以及backUpdate方法可以执行增删改等操作:
//单行插入
public void insert(Customer customer) {
String sql = "INSERT INTO CUSTOMER " +
"(CUST_ID, NAME, AGE) VALUES (?, ?, ?)"
getJdbcTemplate().update(sql,new Object[] {customer.getCustId(),customer.getName(),customer.getAge()});
}
//批量插入
public void bacthInsert(final List<Customer> list) {
getJdbcTemplate().batchUpdate(sql2, new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i) throws SQLException {
Customer cus = list.get(i);
ps.setInt(3, cus.getCustId());
ps.setString(2, cus.getName());
ps.setInt(1, cus.getAge());
}
public int getBatchSize() {
return list.size();
}
});
}
//返回主键
public int create(final Customer customer) {
KeyHolder keyHolder = new GeneratedKeyHolder();
getJdbcTemplate().update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement ps =con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, customer.getCustId());
ps.setString(2, customer.getName());
ps.setInt(3, customer.getAge());
return ps;
}
}, keyHolder
);
return keyHolder.getKey().intValue();
}
namedTemplate对JdbcTemplate的支持:
//单行插入
namedTemplate.update(
"INSERT INTO CUSTOMER (CUST_ID, NAME, AGE) VALUES (:custId, :name, :age)",
new BeanPropertySqlParameterSource(customer));
// 批量插入
SqlParameterSource[] params =
SqlParameterSourceUtils.createBatch(list.toArray());
namedTemplate.batchUpdate(
"INSERT INTO CUSTOMER (CUST_ID, NAME, AGE) VALUES (:custId, :name, :age)",
params);
注:当使用BeanPropertySqlParameterSource进行映射字段时,“CUSTID’将匹配到列名为:”CUSTID’或下划线“CUST_ID”。
3.查询
query方法及queryForXXX方法:用于执行查询相关语句;
//查询单行
String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = ?";
Customer customer = (Customer)getJdbcTemplate().queryForObject(
sql, new Object[] { custId },new RowMapper<Customer>() {
public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
Customer cus = new Customer();
cus.setCustId(rs.getInt("cust_id"));
cus.setAge(rs.getInt("age"));
cus.setName(rs.getString("name"));
return cus;
}
});
或:
Customer customer = (Customer)getJdbcTemplate().queryForObject(
sql, new Object[] { custId },
new BeanPropertyRowMapper(Customer.class));
//查询多行
String sql = "SELECT * FROM CUSTOMER";
List<Customer> customers = new ArrayList<Customer>();
List<Map> rows = getJdbcTemplate().queryForList(sql);
for (Map row : rows) {
Customer customer = new Customer();
customer.setCustId((Long)(row.get("CUST_ID")));
customer.setName((String)row.get("NAME"));
customer.setAge((Integer)row.get("AGE"));
customers.add(customer);
}
或
List<Customer> customers = getJdbcTemplate().query(sql,
new BeanPropertyRowMapper(Customer.class));
注:RowMapper 不支持 queryForList()方法,需要手动映射它
namedTemplate对查询的支持:
解决in数据的问题,在in对应的字段,需要传入List进去,不能传入数组,否则无法读出,且RowMapper支持多个映射。
String sql3 = "select * from customer where cust_id in(:custIds)
Map map = new HashMap();
map.put("custId", custId);
return namedTemplate.query(sql3, map, new RowMapper<Customer>() {
public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
Customer cus = new Customer();
cus.setCustId(rs.getInt("cust_id"));
cus.setAge(rs.getInt("age"));
cus.setName(rs.getString("name"));
return cus;
}
});
返回结果的处理:前面说的rowMapper
// ResultSetExtractor
String listSql = "select * from test";
List result = jdbcTemplate.query(listSql, new ResultSetExtractor<List>() {
@Override
public List extractData(ResultSet rs)
throws SQLException, DataAccessException {
List result = new ArrayList();
while(rs.next()) {
Map row = new HashMap();
row.put(rs.getInt("id"), rs.getString("name"));
result.add(row);
}
return result;
}});
// RowCallbackHandler
String listSql = "select * from test";
final List result = new ArrayList();
jdbcTemplate.query(listSql, new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
Map row = new HashMap();
row.put(rs.getInt("id"), rs.getString("name"));
result.add(row);
}});
4.调用存储过程
call方法:用于执行存储过程、函数相关语句
final String callProcedureSql = "{call text(?, ?)}";
List<SqlParameter> params = new ArrayList<SqlParameter>();
params.add(new SqlParameter("p_in", Types.VARCHAR));
params.add(new SqlOutParameter("p_out", Types.VARCHAR));
Map<String, Object> outValues = this.getJdbcTemplate().call(
new CallableStatementCreator() {
public CallableStatement createCallableStatement(Connection con) throws SQLException {
CallableStatement cstmt = con.prepareCall(callProcedureSql);
cstmt.registerOutParameter(2, Types.VARCHAR);
cstmt.setString(1, "hhhhh");
return cstmt;
}
}, params);
System.out.println(outValues);
注:mysql遇到;就结束问题解决:在存储过程的开头加上“DELIMITER //”,结尾加上“//”就ok了
5.执行操作
可以用于执行任何SQL语句,一般用于执行DDL语句