首页 > 代码库 > (四)Spring 对DAO 的支持

(四)Spring 对DAO 的支持

 

第一节:Spring 对JDBC 的支持

 

1,配置数据源dbcp;

2,使用JdbcTemplate;

3,JdbcDaoSupport 的使用;

4,NamedParameterJdbcTemplate 的使用;支持命名参数变量;

org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate

 

1,使用JdbcTemplate;

T.java:

 1 package com.wishwzp.test; 2  3 import java.util.List; 4  5 import org.junit.Before; 6 import org.junit.Test; 7 import org.springframework.context.ApplicationContext; 8 import org.springframework.context.support.ClassPathXmlApplicationContext; 9 10 import com.wishwzp.model.Student;11 import com.wishwzp.service.StudentService;12 13 14 public class T {15 16     private ApplicationContext ac;17 18     @Before19     public void setUp() throws Exception {20         ac=new ClassPathXmlApplicationContext("beans.xml");21     }22 23     //添加24     @Test25     public void addStudent() {26         StudentService studentService=(StudentService)ac.getBean("studentService");27         int addNums=studentService.addStudent(new Student("王五", 1));28         if(addNums==1){29             System.out.println("添加成功");30         }31     }32     33     //更新34     @Test35     public void updateStudent() {36         StudentService studentService=(StudentService)ac.getBean("studentService");37         int updateNums=studentService.updateStudent(new Student(8,"王五2", 2));38         if(updateNums==1){39             System.out.println("更新成功");40         }41     }42     43     //删除44     @Test45     public void deleteStudent() {46         StudentService studentService=(StudentService)ac.getBean("studentService");47         int deleteNums=studentService.deleteStudent(8);48         if(deleteNums==1){49             System.out.println("删除成功");50         }51     }52     53     //查找54     @Test55     public void findStudents() {56         StudentService studentService=(StudentService)ac.getBean("studentService");57         List<Student> studentList=studentService.findStudents();58         for(Student student:studentList){59             System.out.println(student);60         }61     }62 63 }

 

beans.xml:

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4     xmlns:aop="http://www.springframework.org/schema/aop" 5     xmlns:context="http://www.springframework.org/schema/context" 6     xsi:schemaLocation="http://www.springframework.org/schema/beans 7         http://www.springframework.org/schema/beans/spring-beans.xsd 8         http://www.springframework.org/schema/aop 9         http://www.springframework.org/schema/aop/spring-aop.xsd10         http://www.springframework.org/schema/context11         http://www.springframework.org/schema/context/spring-context.xsd">12         13     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">14         <property name="driverClassName" value="${jdbc.driverClassName}"/>15         <property name="url" value="${jdbc.url}"/>16         <property name="username" value="${jdbc.username}"/>17         <property name="password" value="${jdbc.password}"/>18     </bean>19     20     <context:property-placeholder location="jdbc.properties"/>21     22     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">23         <property name="dataSource" ref="dataSource"></property>24     </bean>25     26     27     <bean id="studentDao" class="com.wishwzp.dao.impl.StudentDaoImpl">28         <property name="jdbcTemplate" ref="jdbcTemplate"></property>29     </bean>30     31     <bean id="studentService" class="com.wishwzp.service.impl.StudentServiceImpl">32         <property name="studentDao" ref="studentDao"></property>33     </bean> 34     35 </beans>

jdbc.properties:

1 jdbc.driverClassName=com.mysql.jdbc.Driver2 jdbc.url=jdbc:mysql://localhost:3306/db_spring?characterEncoding=utf-83 jdbc.username=root4 jdbc.password=root

StudentServiceImpl.java:

 1 package com.wishwzp.service.impl; 2  3 import java.util.List; 4  5 import com.wishwzp.dao.StudentDao; 6 import com.wishwzp.model.Student; 7 import com.wishwzp.service.StudentService; 8  9 public class StudentServiceImpl implements StudentService{10 11     private StudentDao studentDao;12     13     public void setStudentDao(StudentDao studentDao) {14         this.studentDao = studentDao;15     }16 17     @Override18     public int addStudent(Student student) {19         return studentDao.addStudent(student);20     }21 22     @Override23     public int updateStudent(Student student) {24         return studentDao.updateStudent(student);25     }26 27     @Override28     public int deleteStudent(int id) {29         return studentDao.deleteStudent(id);30     }31 32     @Override33     public List<Student> findStudents() {34         return studentDao.findStudents();35     }36 37 }

StudentService.java:

 1 package com.wishwzp.service; 2  3 import java.util.List; 4  5 import com.wishwzp.model.Student; 6  7 public interface StudentService { 8  9     public int addStudent(Student student);10     11     public int updateStudent(Student student);12     13     public int deleteStudent(int id);14     15     public List<Student> findStudents();16 }

 

StudentDaoImpl.java:

 1 package com.wishwzp.dao.impl; 2  3 import java.sql.ResultSet; 4 import java.sql.SQLException; 5 import java.util.ArrayList; 6 import java.util.List; 7  8 import org.springframework.jdbc.core.JdbcTemplate; 9 import org.springframework.jdbc.core.RowCallbackHandler;10 11 import com.wishwzp.dao.StudentDao;12 import com.wishwzp.model.Student;13 14 public class StudentDaoImpl implements StudentDao{15 16     private JdbcTemplate jdbcTemplate;17     18     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {19         this.jdbcTemplate = jdbcTemplate;20     }21 22     @Override23     public int addStudent(Student student) {24         String sql="insert into t_student values(null,?,?)";25         Object []params=new Object[]{student.getName() , student.getAge()};26         int addjdbcTemplate = jdbcTemplate.update(sql,params);27         return addjdbcTemplate;28     }29 30     @Override31     public int updateStudent(Student student) {32         String sql="update t_student set name=?,age=? where id=?";33         Object []params=new Object[]{student.getName() , student.getAge() , student.getId()};34         int updatejdbcTemplate = jdbcTemplate.update(sql,params);35         return updatejdbcTemplate;36     }37 38     @Override39     public int deleteStudent(int id) {40         String sql="delete from t_student where id=?";41         Object []params=new Object[]{ id };42         int deletejdbcTemplate = jdbcTemplate.update(sql,params);43         return deletejdbcTemplate;44     }45 46     @Override47     public List<Student> findStudents() {48         String sql="select * from t_student";49         final List<Student> studentList=new ArrayList<Student>();50         jdbcTemplate.query(sql, new RowCallbackHandler(){51 52             @Override53             public void processRow(ResultSet rs) throws SQLException {54                 Student student=new Student();55                 student.setId(rs.getInt("id"));56                 student.setName(rs.getString("name"));57                 student.setAge(rs.getInt("age"));58                 studentList.add(student);59             }60         });61         return studentList;62     }63 64 }

StudentDao.java:

 1 package com.wishwzp.dao; 2  3 import java.util.List; 4  5 import com.wishwzp.model.Student; 6  7 public interface StudentDao { 8  9     public int addStudent(Student student);10     11     public int updateStudent(Student student);12     13     public int deleteStudent(int id);14     15     public List<Student> findStudents();16 }

Student.java:

 1 package com.wishwzp.model; 2  3 public class Student { 4  5     private int id; 6     private String name; 7     private int age; 8      9     public Student() {10         super();11         // TODO Auto-generated constructor stub12     }13     14     public Student(String name, int age) {15         super();16         this.name = name;17         this.age = age;18     }19 20     public Student(int id, String name, int age) {21         super();22         this.id = id;23         this.name = name;24         this.age = age;25     }26 27 28     public int getId() {29         return id;30     }31     public void setId(int id) {32         this.id = id;33     }34     public String getName() {35         return name;36     }37     public void setName(String name) {38         this.name = name;39     }40     public int getAge() {41         return age;42     }43     public void setAge(int age) {44         this.age = age;45     }46 47     @Override48     public String toString() {49         return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";50     }51     52 }

 

运行结果就是每一个对数据库的CRUD

 

 

3,JdbcDaoSupport 的使用;

T.java:

 1 package com.wishwzp.test; 2  3 import java.util.List; 4  5 import org.junit.Before; 6 import org.junit.Test; 7 import org.springframework.context.ApplicationContext; 8 import org.springframework.context.support.ClassPathXmlApplicationContext; 9 10 import com.wishwzp.model.Student;11 import com.wishwzp.service.StudentService;12 13 14 public class T {15 16     private ApplicationContext ac;17 18     @Before19     public void setUp() throws Exception {20         ac=new ClassPathXmlApplicationContext("beans.xml");21     }22 23     @Test24     public void addStudent() {25         StudentService studentService=(StudentService)ac.getBean("studentService");26         int addNums=studentService.addStudent(new Student("王五", 1));27         if(addNums==1){28             System.out.println("添加成功");29         }30     }31     32     @Test33     public void updateStudent() {34         StudentService studentService=(StudentService)ac.getBean("studentService");35         int updateNums=studentService.updateStudent(new Student(4,"王五2", 2));36         if(updateNums==1){37             System.out.println("更新成功");38         }39     }40     41     @Test42     public void deleteStudent() {43         StudentService studentService=(StudentService)ac.getBean("studentService");44         int deleteNums=studentService.deleteStudent(10);45         if(deleteNums==1){46             System.out.println("删除成功");47         }48     }49     50     @Test51     public void findStudents() {52         StudentService studentService=(StudentService)ac.getBean("studentService");53         List<Student> studentList=studentService.findStudents();54         for(Student student:studentList){55             System.out.println(student);56         }57     }58     59     60 61 }

 

beans.xml:

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4     xmlns:aop="http://www.springframework.org/schema/aop" 5     xmlns:context="http://www.springframework.org/schema/context" 6     xsi:schemaLocation="http://www.springframework.org/schema/beans 7         http://www.springframework.org/schema/beans/spring-beans.xsd 8         http://www.springframework.org/schema/aop 9         http://www.springframework.org/schema/aop/spring-aop.xsd10         http://www.springframework.org/schema/context11         http://www.springframework.org/schema/context/spring-context.xsd">12         13     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">14         <property name="driverClassName" value="${jdbc.driverClassName}"/>15         <property name="url" value="${jdbc.url}"/>16         <property name="username" value="${jdbc.username}"/>17         <property name="password" value="${jdbc.password}"/>18     </bean>19     20     <context:property-placeholder location="jdbc.properties"/>21     22  23     24     <bean id="studentDao" class="com.wishwzp.dao.impl.StudentDaoImpl">25         <property name="dataSource" ref="dataSource"></property>26     </bean> 27     28     <bean id="studentService" class="com.wishwzp.service.impl.StudentServiceImpl">29         <property name="studentDao" ref="studentDao"></property>30     </bean> 31     32 </beans>

jdbc.properties:

1 jdbc.driverClassName=com.mysql.jdbc.Driver2 jdbc.url=jdbc:mysql://localhost:3306/db_spring?characterEncoding=utf-83 jdbc.username=root4 jdbc.password=root

StudentServiceImpl.java:

 1 package com.wishwzp.service.impl; 2  3 import java.util.List; 4  5 import com.wishwzp.dao.StudentDao; 6 import com.wishwzp.model.Student; 7 import com.wishwzp.service.StudentService; 8  9 public class StudentServiceImpl implements StudentService{10 11     private StudentDao studentDao;12     13     public void setStudentDao(StudentDao studentDao) {14         this.studentDao = studentDao;15     }16 17     @Override18     public int addStudent(Student student) {19         return studentDao.addStudent(student);20     }21 22     @Override23     public int updateStudent(Student student) {24         return studentDao.updateStudent(student);25     }26 27     @Override28     public int deleteStudent(int id) {29         return studentDao.deleteStudent(id);30     }31 32     @Override33     public List<Student> findStudents() {34         return studentDao.findStudents();35     }36 37     38 39 }

StudentService.java:

 1 package com.wishwzp.service; 2  3 import java.util.List; 4  5 import com.wishwzp.model.Student; 6  7 public interface StudentService { 8  9     public int addStudent(Student student);10     11     public int updateStudent(Student student);12     13     public int deleteStudent(int id);14     15     public List<Student> findStudents();16 }

StudentDaoImpl.java:

 1 package com.wishwzp.dao.impl; 2  3 import java.sql.ResultSet; 4 import java.sql.SQLException; 5 import java.util.ArrayList; 6 import java.util.List; 7  8 import org.springframework.jdbc.core.JdbcTemplate; 9 import org.springframework.jdbc.core.RowCallbackHandler;10 import org.springframework.jdbc.core.support.JdbcDaoSupport;11 12 import com.wishwzp.dao.StudentDao;13 import com.wishwzp.model.Student;14 15 public class StudentDaoImpl extends JdbcDaoSupport implements StudentDao{16 17     @Override18     public int addStudent(Student student) {19         String sql="insert into t_student values(null,?,?)";20         Object []params=new Object[]{student.getName(),student.getAge()};21         int addgetJdbcTemplate = getJdbcTemplate().update(sql,params);22         return addgetJdbcTemplate;23         //return this.getJdbcTemplate().update(sql,params);24     }25 26     @Override27     public int updateStudent(Student student) {28         String sql="update t_student set name=?,age=? where id=?";29         Object []params=new Object[]{student.getName() , student.getAge() , student.getId()};30         int updategetJdbcTemplate = getJdbcTemplate().update(sql,params);31         return updategetJdbcTemplate;32         //return this.getJdbcTemplate().update(sql,params);33     }34 35     @Override36     public int deleteStudent(int id) {37         String sql="delete from t_student where id=?";38         Object []params=new Object[]{id};39         int deletegetJdbcTemplate = getJdbcTemplate().update(sql,params);40         return deletegetJdbcTemplate;41         //return this.getJdbcTemplate().update(sql,params);42     }43 44     @Override45     public List<Student> findStudents() {46         String sql="select * from t_student";47         final List<Student> studentList=new ArrayList<Student>();48         this.getJdbcTemplate().query(sql, new RowCallbackHandler(){49 50             @Override51             public void processRow(ResultSet rs) throws SQLException {52                 Student student=new Student();53                 student.setId(rs.getInt("id"));54                 student.setName(rs.getString("name"));55                 student.setAge(rs.getInt("age"));56                 studentList.add(student);57             }58             59         });60         return studentList;61     }62 63 }

StudentDao.java:

 1 package com.wishwzp.dao; 2  3 import java.util.List; 4  5 import com.wishwzp.model.Student; 6  7 public interface StudentDao { 8  9     public int addStudent(Student student);10     11     public int updateStudent(Student student);12     13     public int deleteStudent(int id);14     15     public List<Student> findStudents();16 }

Student.java:

 1 package com.wishwzp.model; 2  3 public class Student { 4  5     private int id; 6     private String name; 7     private int age; 8      9     10     11     public Student() {12         super();13         // TODO Auto-generated constructor stub14     }15     16     17     public Student(String name, int age) {18         super();19         this.name = name;20         this.age = age;21     }22 23     24 25     public Student(int id, String name, int age) {26         super();27         this.id = id;28         this.name = name;29         this.age = age;30     }31 32 33     public int getId() {34         return id;35     }36     public void setId(int id) {37         this.id = id;38     }39     public String getName() {40         return name;41     }42     public void setName(String name) {43         this.name = name;44     }45     public int getAge() {46         return age;47     }48     public void setAge(int age) {49         this.age = age;50     }51 52 53     @Override54     public String toString() {55         return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";56     }57     58     59     60 }

 

运行结果就是每一个对数据库的CRUD

 

 

4,NamedParameterJdbcTemplate 的使用;支持命名参数变量;

T.java:

 1 package com.wishwzp.test; 2  3 import java.util.List; 4  5 import org.junit.Before; 6 import org.junit.Test; 7 import org.springframework.context.ApplicationContext; 8 import org.springframework.context.support.ClassPathXmlApplicationContext; 9 10 import com.wishwzp.model.Student;11 import com.wishwzp.service.StudentService;12 13 14 public class T {15 16     private ApplicationContext ac;17 18     @Before19     public void setUp() throws Exception {20         ac=new ClassPathXmlApplicationContext("beans.xml");21     }22 23     @Test24     public void addStudent() {25         StudentService studentService=(StudentService)ac.getBean("studentService");26         int addNums=studentService.addStudent(new Student("王五", 1));27         if(addNums==1){28             System.out.println("添加成功");29         }30     }31     32     @Test33     public void updateStudent() {34         StudentService studentService=(StudentService)ac.getBean("studentService");35         int updateNums=studentService.updateStudent(new Student(11,"王五2", 2));36         if(updateNums==1){37             System.out.println("更新成功");38         }39     }40     41     @Test42     public void deleteStudent() {43         StudentService studentService=(StudentService)ac.getBean("studentService");44         int deleteNums=studentService.deleteStudent(11);45         if(deleteNums==1){46             System.out.println("删除成功");47         }48     }49     50     @Test51     public void findStudents() {52         StudentService studentService=(StudentService)ac.getBean("studentService");53         List<Student> studentList=studentService.findStudents();54         for(Student student:studentList){55             System.out.println(student);56         }57     }58     59     60 61 }

 

beans.xml:

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4     xmlns:aop="http://www.springframework.org/schema/aop" 5     xmlns:context="http://www.springframework.org/schema/context" 6     xsi:schemaLocation="http://www.springframework.org/schema/beans 7         http://www.springframework.org/schema/beans/spring-beans.xsd 8         http://www.springframework.org/schema/aop 9         http://www.springframework.org/schema/aop/spring-aop.xsd10         http://www.springframework.org/schema/context11         http://www.springframework.org/schema/context/spring-context.xsd">12         13     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">14         <property name="driverClassName" value="${jdbc.driverClassName}"/>15         <property name="url" value="${jdbc.url}"/>16         <property name="username" value="${jdbc.username}"/>17         <property name="password" value="${jdbc.password}"/>18     </bean>19     20     <context:property-placeholder location="jdbc.properties"/>21     22     <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">23         <constructor-arg ref="dataSource"></constructor-arg>24     </bean>25     26     27     <bean id="studentDao" class="com.wishwzp.dao.impl.StudentDaoImpl">28         <property name="namedParameterJdbcTemplate" ref="namedParameterJdbcTemplate"></property>29     </bean> 30     31     <bean id="studentService" class="com.wishwzp.service.impl.StudentServiceImpl">32         <property name="studentDao" ref="studentDao"></property>33     </bean> 34     35 </beans>

jdbc.properties:

1 jdbc.driverClassName=com.mysql.jdbc.Driver2 jdbc.url=jdbc:mysql://localhost:3306/db_spring?characterEncoding=utf-83 jdbc.username=root4 jdbc.password=root

StudentServiceImpl.java:

 1 package com.wishwzp.service.impl; 2  3 import java.util.List; 4  5 import com.wishwzp.dao.StudentDao; 6 import com.wishwzp.model.Student; 7 import com.wishwzp.service.StudentService; 8  9 public class StudentServiceImpl implements StudentService{10 11     private StudentDao studentDao;12     13     public void setStudentDao(StudentDao studentDao) {14         this.studentDao = studentDao;15     }16 17     @Override18     public int addStudent(Student student) {19         return studentDao.addStudent(student);20     }21 22     @Override23     public int updateStudent(Student student) {24         return studentDao.updateStudent(student);25     }26 27     @Override28     public int deleteStudent(int id) {29         return studentDao.deleteStudent(id);30     }31 32     @Override33     public List<Student> findStudents() {34         return studentDao.findStudents();35     }36 37     38 39 }

StudentService.java:

 1 package com.wishwzp.service; 2  3 import java.util.List; 4  5 import com.wishwzp.model.Student; 6  7 public interface StudentService { 8  9     public int addStudent(Student student);10     11     public int updateStudent(Student student);12     13     public int deleteStudent(int id);14     15     public List<Student> findStudents();16 }

StudentDaoImpl.java:

 1 package com.wishwzp.dao.impl; 2  3 import java.sql.ResultSet; 4 import java.sql.SQLException; 5 import java.util.ArrayList; 6 import java.util.List; 7  8 import org.springframework.jdbc.core.JdbcTemplate; 9 import org.springframework.jdbc.core.RowCallbackHandler;10 import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;11 import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;12 13 import com.wishwzp.dao.StudentDao;14 import com.wishwzp.model.Student;15 16 public class StudentDaoImpl implements StudentDao{17 18     private NamedParameterJdbcTemplate namedParameterJdbcTemplate;19     20     public void setNamedParameterJdbcTemplate(21             NamedParameterJdbcTemplate namedParameterJdbcTemplate) {22         this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;23     }24 25     @Override26     public int addStudent(Student student) {27         String sql="insert into t_student values(null,:name,:age)";28         MapSqlParameterSource sps=new MapSqlParameterSource();29         sps.addValue("name", student.getName());30         sps.addValue("age", student.getAge());31         return namedParameterJdbcTemplate.update(sql,sps);32     }33 34     @Override35     public int updateStudent(Student student) {36         String sql="update t_student set name=:name,age=:age where id=:id";37         MapSqlParameterSource sps=new MapSqlParameterSource();38         sps.addValue("name", student.getName());39         sps.addValue("age", student.getAge());40         sps.addValue("id", student.getId());41         return namedParameterJdbcTemplate.update(sql,sps);42     }43 44     @Override45     public int deleteStudent(int id) {46         String sql="delete from t_student where id=:id";47         MapSqlParameterSource sps=new MapSqlParameterSource();48         sps.addValue("id", id);49         return namedParameterJdbcTemplate.update(sql,sps);50     }51 52     @Override53     public List<Student> findStudents() {54         String sql="select * from t_student";55         final List<Student> studentList=new ArrayList<Student>();56         namedParameterJdbcTemplate.query(sql, new RowCallbackHandler(){57 58             @Override59             public void processRow(ResultSet rs) throws SQLException {60                 Student student=new Student();61                 student.setId(rs.getInt("id"));62                 student.setName(rs.getString("name"));63                 student.setAge(rs.getInt("age"));64                 studentList.add(student);65             }66             67         });68         return studentList;69     }70 71 }

StudentDao.java:

 1 package com.wishwzp.dao; 2  3 import java.util.List; 4  5 import com.wishwzp.model.Student; 6  7 public interface StudentDao { 8  9     public int addStudent(Student student);10     11     public int updateStudent(Student student);12     13     public int deleteStudent(int id);14     15     public List<Student> findStudents();16 }

Student.java:

 1 package com.wishwzp.model; 2  3 public class Student { 4  5     private int id; 6     private String name; 7     private int age; 8      9     10     11     public Student() {12         super();13         // TODO Auto-generated constructor stub14     }15     16     17     public Student(String name, int age) {18         super();19         this.name = name;20         this.age = age;21     }22 23     24 25     public Student(int id, String name, int age) {26         super();27         this.id = id;28         this.name = name;29         this.age = age;30     }31 32 33     public int getId() {34         return id;35     }36     public void setId(int id) {37         this.id = id;38     }39     public String getName() {40         return name;41     }42     public void setName(String name) {43         this.name = name;44     }45     public int getAge() {46         return age;47     }48     public void setAge(int age) {49         this.age = age;50     }51 52 53     @Override54     public String toString() {55         return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";56     }57     58     59     60 }

 

运行结果就是每一个对数据库的CRUD

 

 

第二节:Spring 对Hibernate 的支持

 

后面Spring 整合Hibernate 的时候会提的。

 

(四)Spring 对DAO 的支持