- 在学习spring过程中,关于spring的数据库CRUD问题,和我们之前没有使用spring时写的CRUD语句变化不大
- 使用RowMapper的接口就是用来把数据中的列字段和java Bean中的属性对应上,这样就可以赋值了。也像JDBC中的bean.setName(rs.getString(“name”);Spring把这段代码抽象出来写成RowMapper.
- 下面来看一下具体怎么写(举一个例子来说明)
1.首先我们写一个实体类
package com.itheima.domain;
import lombok.Getter;
import lombok.Setter;
@Setter@Getter
public class Account {
private Integer id;
private String name;
private Float money;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
2.然后我们写一个AccountRowMapper类,把结果集中的数据封装到Account中,然后由Spring把每个Account加到集合中。
package com.itheima.jdbctemplate;
import com.itheima.domain.Account;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
public class AccountRowMapper implements RowMapper<Account> {
//把结果集中的数据封装到Account中,然后由spring把每个Account加到集合中
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account = new Account();
account.setId(resultSet.getInt("id"));
account.setName(resultSet.getString("name"));
account.setMoney(resultSet.getFloat("money"));
return account;
}
}
3.然后我们在对数据库进行CRUD操作
package com.itheima.jdbctemplate;
import com.itheima.domain.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class jdbctemplateDemo3 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbctemplateDemo1",JdbcTemplate.class);
//3.执行语句
//保存
//jdbcTemplate.update("insert into account(name,money)values(?,?)","eee",3333f);
//更新
//查询所有
List<Account> accounts = jdbcTemplate.query("select * from account where money > ?",new AccountRowMapper(),1000f);
for(Account account : accounts){
System.out.println(account);
}
//查询一个
//查询返回一行一列
}
}