class StudentDaoJDBCImpl
implements StudentDao {
private JdbcTemplate template;
//template的setter.getter方法
@Override
public
void delete(Student s) {
deleteById(s.getId());
}
@Override
public
void deleteById(Integer id) {
String sql =
“delete from spring_student where id=?”;
Object[] args = { id };
// 数组元素依次对应sql语句中的?
template.update(sql, args);
// 只需传sql语句和参数数组,template会自动加载驱动,创建连结,执行sql语句,并且进行事务处理
}
@Override
public
void insert(Student s) {
String sql =
“insert into spring_student(id,name,birthday) values(spring_stu_seq.nextval,?,?)”;
Object[] args = { s.getName(), s.getBirthday() };
//template会对Date类型数据进行转化
template.update(sql, args);
}
@Override
public Student queryById(Integer id) {
String sql =
“select id,name,birthday from spring_student where id=?”;
Object[] args = { id };
final Student s =
new Student();
template.query(sql, args,
new RowCallbackHandler() {
//它要求程序员自己在RowCallbackHandler类型对象的proce***ow方法中对结果集进行处理
@Override
public
void proce***ow(ResultSet rs)
throws SQLException {
if (!(rs.isAfterLast())) {
// 把查询结果封装到一个对象中
s.setId(rs.getInt(1));
s.setName(rs.getString(2));
s.setBirthday(rs.getDate(3));
}
}
});
if (s.getId() ==
null) {
return
null;
}
else {
return s;
}
}
@Override
public List<Student> queryAll() {
String sql=
“select id,name,birthday from spring_student”;
List<Student> ret=template.query(sql,
new RowMapper(){
//它要求程序员自己在RowMapper类型对象的mapRow方法中说明结果集中每条记录如何封装成一个对象,
//template.query方法会自动把对象加入到集合中。
@Override
public Object mapRow(ResultSet rs,
int rowNum)
throws SQLException {
//rs:结果集
//rowNum:迭代次数
Student s=
new Student();
s.setId(rs.getInt(1));
s.setName(rs.getString(2));
s.setBirthday(rs.getDate(3));
return s;
}
});
return ret;
}
}
beans
>
<
bean
id
=”dataSource”
class
=”org.apache.commons.dbcp.BasicDataSource”
>
<
property
name
=”driverClassName”
>
<
value
>oracle.jdbc.driver.OracleDriver
</
value
>
</
property
>
<
property
name
=”url”
>
<
value
>jdbc:oracle:thin:@localhost:1521:orcl10
</
value
>
</
property
>
<
property
name
=”username”
>
<
value
>scott
</
value
>
</
property
>
<
property
name
=”password”
>
<
value
>yf123
</
value
>
</
property
>
</
bean
>
<
bean
id
=”jdbcTemplate”
class
=”org.springframework.jdbc.core.JdbcTemplate”
>
<
property
name
=”dataSource”
>
<
ref
local
=”dataSource”
/>
</
property
>
</
bean
>
<
bean
id
=”dao”
class
=”com.yangfei.spring.jdbc.dao.StudentDaoJDBCImpl”
>
<
property
name
=”template”
>
<
ref
local
=”jdbcTemplate”
/>
</
property
>
</
bean
>
</
beans
>
static
void main(String[] args) {
ApplicationContext ctx=
new ClassPathXmlApplicationContext(
“jdbc.xml”);
StudentDao dao=(StudentDao)ctx.getBean(
“dao”);
System.out.println(dao.queryById(2));
//dao.deleteById(1);
Student s=
new Student();
s.setName(
“xiaozhang”);
s.setBirthday(
new Date());
dao.insert(s);
转载于:https://blog.51cto.com/yangfei520/246476
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/110829.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...