spring4-4-jdbc-02
时间:2021-07-01 10:21:17
帮助过:4人阅读
com.l1.spring.jdbc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
@Repository
public class EmployeeDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public Employee get(
int id){
String sql = "select id,name,email from employees where id=?"
;
RowMapper<Employee> rowMapper =
new BeanPropertyRowMapper<>(Employee.
class);
Employee employee =
jdbcTemplate.queryForObject(sql, rowMapper,id);
return employee;
}
}
第四条使用:
/**
* 不推荐使用 JdbcDaoSupport, 而推荐直接使用 JdbcTempate 作为 Dao 类的成员变量
*/
@Repository
public class DepartmentDao extends JdbcDaoSupport{
@Autowired
public void setDataSource2(DataSource dataSource){
setDataSource(dataSource);
}
public Department get(Integer id){
String sql = "SELECT id, dept_name name FROM departments WHERE id = ?";
RowMapper<Department> rowMapper = new BeanPropertyRowMapper<>(Department.class);
return getJdbcTemplate().queryForObject(sql, rowMapper, id);
}
}
spring4-4-jdbc-02
标签: