实现步骤:
在applicationContext.xml配置:
<!--获取数据源-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<!--拿到连接数据库的信息-->
<property name="url" value="jdbc:mysql://localhost:3306/account?useUnicodpassworde=true&characterEncoding=utf-8"></property>
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!--spring提供操作数据库的类-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置dao层-->
<bean id="accountDao" class="com.offcn.dao.impl.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<!--配置service层-->
<bean id="accountService" class="com.offcn.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
在dao方法里面实现增删改查:
查询的时候要麻烦一点,需要有
RowMapper rowMapper=new RowMapper()
eg:一个完整的查询应该如下调用queryForObject()方法:
public Account selectById(int aid) {
String sql="select * from account where aid=?";
Object [] objects={aid};
/*返回的每一行数据都在这个类里,第一个参数是返回的结果值,第二个参数是当前索引*/
RowMapper<Account> rowMapper=new RowMapper<Account>() {
@Override
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account=new Account();
account.setAid(resultSet.getInt("aid"));
account.setAbalance(resultSet.getDouble("ablance"));
return account;
}
};
//如果是查询所有这里返回的是L
Account account1= jdbcTemplate.queryForObject(sql, objects, rowMapper);
return account1;
}
增删改:调用update()方法:
以增加为例子:
public int add(Account account) {
String sql="insert into account (ablance) value(?)";
Object [] objects={account.getAbalance()};
int i = jdbcTemplate.update(sql, objects);
return i;
}