纯JDBC操作, 对某些项目来说, 也许更好, Spring JDBC Framework让你不用关心Connection, Statement, ResultSet.
定义数据源
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:/comp/env/jdbc/oracle</value>
</property>
</bean>
定义事务管理器
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
定义dao
<bean id="customerDAO" class="com.waterye.dao.impl.CustomerDAOImpl">
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager" />
</bean>
demo
public class CustomerDaoImpl extends JdbcDaoSupport implements CustomerDAO {
private DataSource dataSource;
pirvate TransactionManager transactionManager;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void setTransactionManager(DataSourceTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public Map get(Integer id) throws Exception {
String querySql = "select * from customer where id = ?";
return getJdbcTemplate().queryForMap(querySql, new Object[] { id });
}
public void insert(final Map customer) throws Exception {
String seqSql = "select customer_seql.nextval from dual";
String insertSql = "insert into customer (id, code, name, status) values (?, ?, ?, ?)";
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
JdbcTemplate jdbcTemplate = getJdbcTemplate();
int id = jdbcTemplate.queryForInt(seqSql);
Object[] params = new Object[] { new Integer(id), customer.get("code"), customer.get("name"), map.get("status") };
jdbcTemplate.update(insertSql, params);
}
}
}
public void update(final Map customer) throws Exception {
//
}
public void delete(Integer id) throws Exception {
String deleteSql = "delete from customer where id = ?";
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
getJdbcTemplate().update(deleteSql, new Object[] { id });
}
}
}
public List findValidCustomers() throws Exception {
String querySql = "select * from customer where status = 'valid' order by code";
return getJdbcTemplate().query(querySql, new OracleColumnMapRowMapper());
}
}
说明:
1. 没有使用声明性事务, 使用编程式事务
2. 没有使用POJO模式,使用HashMap, (ActiveMapper还在sandbax状态)
3. OracleColumnMapRowMapper implements RowMapper, 实现oracle风格到java bean风格mapping
如: 字段customer_id 对应rowMap.get("customerId");
没有评论:
发表评论