以下示例将展示如何使用Spring jdbc进行查询数据记录,将从student
表中查询记录。
语法:
String selectQuery = "select * from student";
List <Student> students = jdbcTemplateObject.query(selectQuery, new StudentMapper());
在上面语法中 -
selectQuery
- 选择查询学生数据记录。jdbcTemplateObject
-StudentJDBCTemplate
对象将Student
对象插入到数据库中。
StudentMapper
-StudentMapper
是一个RowMapper对象,用于将每个获取的记录映射到Student
对象。
查询数据方法
public List<Student> listStudents() {
String sql = "select * from student";
List<Student> students = jdbcTemplateObject.query(sql, new StudentMapper());
return students;
}
执行程序:
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("application-beans.xml");
StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate");
System.out.println("------Listing Multiple Records--------");
List<Student> students = studentJDBCTemplate.listStudents();
for (Student record : students) {
System.out.print("ID : " + record.getId());
System.out.print(",Name : " + record.getName());
System.out.println(",Age : " + record.getAge());
}
}
}
输出结果:
ID : 10,Name : Allen,Age : 17
ID : 11,Name : Ray,Age : 18
ID : 12,Name : Mark,Age : 20
ID : 13,Name : Allen,Age : 17
ID : 14,Name : Ray,Age : 18
ID : 15,Name : Mark,Age : 20
ID : 16,Name : Allen,Age : 17
ID : 17,Name : Ray,Age : 18
ID : 18,Name : Mark,Age : 20
ID : 19,Name : Allen,Age : 17
ID : 20,Name : Ray,Age : 18
ID : 21,Name : Mark,Age : 20