Spring JDBC---jdbcTemplate数据查询方法
查询单条数据
jdbcTemplate.queryForObject()
查询复合数据
jdbcTemplate.query()
无法进行实体类映射
使用jdbcTemplate.queryForList()保存查询结果数据,结果封装成map对象
在EmployeeDao中增加查询方法
package com.spring.jdbc.dao;
import com.spring.jdbc.entity.Employee;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.util.Map;
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
public Employee findById(Integer eno){
String sql = "select * from employee where eno = ?";
//jdbcTemplate.queryForObject()查询单条数据
Employee employee = jdbcTemplate.queryForObject(sql,new Object[]{eno},new BeanPropertyRowMapper<Employee>(Employee.class));
return employee;
}
public List<Employee> findByDname(String dname){
String sql = "select * from employee where dname = ?";
//jdbcTemplate.query()查询复合数据
List<Employee> list = jdbcTemplate.query(sql, new Object[]{dname}, new BeanPropertyRowMapper<Employee>(Employee.class));
return list;
}
public List<Map<String, Object>> findMapByDname(String dname){
String sql = "select eno as empno,salary as s from employee where dname = ?";
//无法进行实体类映射,使用jdbcTemplate.queryForList()保存查询结果数据,结果封装成map对象
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, new Object[]{dname});
return maps;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
在测试类中调用
import com.spring.jdbc.dao.EmployeeDao;
import com.spring.jdbc.entity.Employee;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class JdbcTemplateTestor {
@Resource
private EmployeeDao employeeDao;
@Test
public void testFindById(){
Employee employee = employeeDao.findById(3308);
System.out.println(employee);
}
@Test
public void testFindByDname(){
System.out.println(employeeDao.findByDname("市场部"));
}
@Test
public void testFindMapByDname(){
System.out.println(employeeDao.findMapByDname("研发部"));
}
}




浙公网安备 33010602011771号