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語句