标签:
简化 JDBC 模板查询
第二条示例:
package 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); } }
标签:
原文地址:http://www.cnblogs.com/a198720/p/4613944.html