课程表

Spring 入门

Spring IoC 容器

Spring 依赖注入

Spring Beans 自动装配

Spring 基于注解的配置

Spring 框架

Spring 事务管理

Spring Web MVC 框架

工具箱
速查手册

Spring JDBC 示例

当前位置:免费教程 » Java相关 » Spring

想要理解带有 jdbc 模板类的 Spring JDBC 框架的相关概念,让我们编写一个简单的示例,来实现下述 Student 表的所有 CRUD 操作。

  1. CREATE TABLE Student(
  2. ID INT NOT NULL AUTO_INCREMENT,
  3. NAME VARCHAR(20) NOT NULL,
  4. AGE INT NOT NULL,
  5. PRIMARY KEY (ID)
  6. );

在继续之前,让我们适当地使用 Eclipse IDE 并按照如下所示的步骤创建一个 Spring 应用程序:

步骤 描述
1 创建一个名为 SpringExample 的项目,并在创建的项目中的 src 文件夹下创建包 com.tutorialspoint
2 使用 Add External JARs 选项添加必需的 Spring 库,解释见 Spring Hello World Example 章节。
3 在项目中添加 Spring JDBC 指定的最新的库 mysql-connector-java.jarorg.springframework.jdbc.jarorg.springframework.transaction.jar。如果这些库不存在,你可以下载它们。
4 创建 DAO 接口 StudentDAO 并列出所有必需的方法。尽管这一步不是必需的而且你可以直接编写 StudentJDBCTemplate 类,但是作为一个好的实践,我们最好还是做这一步。
5 com.tutorialspoint 包下创建其他的必需的 Java 类 StudentStudentMapperStudentJDBCTemplateMainApp
6 确保你已经在 TEST 数据库中创建了 Student 表。并确保你的 MySQL 服务器运行正常,且你可以使用给出的用户名和密码读/写访问数据库。
7 src 文件夹下创建 Beans 配置文件 Beans.xml
8 最后一步是创建所有的 Java 文件和 Bean 配置文件的内容并按照如下所示的方法运行应用程序。

以下是数据访问对象接口文件 StudentDAO.java 的内容:

  1. package com.tutorialspoint;
  2. import java.util.List;
  3. import javax.sql.DataSource;
  4. public interface StudentDAO {
  5. /**
  6. * This is the method to be used to initialize
  7. * database resources ie. connection.
  8. */
  9. public void setDataSource(DataSource ds);
  10. /**
  11. * This is the method to be used to create
  12. * a record in the Student table.
  13. */
  14. public void create(String name, Integer age);
  15. /**
  16. * This is the method to be used to list down
  17. * a record from the Student table corresponding
  18. * to a passed student id.
  19. */
  20. public Student getStudent(Integer id);
  21. /**
  22. * This is the method to be used to list down
  23. * all the records from the Student table.
  24. */
  25. public List<Student> listStudents();
  26. /**
  27. * This is the method to be used to delete
  28. * a record from the Student table corresponding
  29. * to a passed student id.
  30. */
  31. public void delete(Integer id);
  32. /**
  33. * This is the method to be used to update
  34. * a record into the Student table.
  35. */
  36. public void update(Integer id, Integer age);
  37. }

下面是 Student.java 文件的内容:

  1. package com.tutorialspoint;
  2. public class Student {
  3. private Integer age;
  4. private String name;
  5. private Integer id;
  6. public void setAge(Integer age) {
  7. this.age = age;
  8. }
  9. public Integer getAge() {
  10. return age;
  11. }
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15. public String getName() {
  16. return name;
  17. }
  18. public void setId(Integer id) {
  19. this.id = id;
  20. }
  21. public Integer getId() {
  22. return id;
  23. }
  24. }

以下是 StudentMapper.java 文件的内容:

  1. package com.tutorialspoint;
  2. import java.sql.ResultSet;
  3. import java.sql.SQLException;
  4. import org.springframework.jdbc.core.RowMapper;
  5. public class StudentMapper implements RowMapper<Student> {
  6. public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
  7. Student student = new Student();
  8. student.setId(rs.getInt("id"));
  9. student.setName(rs.getString("name"));
  10. student.setAge(rs.getInt("age"));
  11. return student;
  12. }
  13. }

下面是为定义的 DAO 接口 StudentDAO 的实现类文件 StudentJDBCTemplate.java

  1. package com.tutorialspoint;
  2. import java.util.List;
  3. import javax.sql.DataSource;
  4. import org.springframework.jdbc.core.JdbcTemplate;
  5. public class StudentJDBCTemplate implements StudentDAO {
  6. private DataSource dataSource;
  7. private JdbcTemplate jdbcTemplateObject;
  8. public void setDataSource(DataSource dataSource) {
  9. this.dataSource = dataSource;
  10. this.jdbcTemplateObject = new JdbcTemplate(dataSource);
  11. }
  12. public void create(String name, Integer age) {
  13. String SQL = "insert into Student (name, age) values (?, ?)";
  14. jdbcTemplateObject.update( SQL, name, age);
  15. System.out.println("Created Record Name = " + name + " Age = " + age);
  16. return;
  17. }
  18. public Student getStudent(Integer id) {
  19. String SQL = "select * from Student where id = ?";
  20. Student student = jdbcTemplateObject.queryForObject(SQL,
  21. new Object[]{id}, new StudentMapper());
  22. return student;
  23. }
  24. public List<Student> listStudents() {
  25. String SQL = "select * from Student";
  26. List <Student> students = jdbcTemplateObject.query(SQL,
  27. new StudentMapper());
  28. return students;
  29. }
  30. public void delete(Integer id){
  31. String SQL = "delete from Student where id = ?";
  32. jdbcTemplateObject.update(SQL, id);
  33. System.out.println("Deleted Record with ID = " + id );
  34. return;
  35. }
  36. public void update(Integer id, Integer age){
  37. String SQL = "update Student set age = ? where id = ?";
  38. jdbcTemplateObject.update(SQL, age, id);
  39. System.out.println("Updated Record with ID = " + id );
  40. return;
  41. }
  42. }

以下是 MainApp.java 文件的内容:

  1. package com.tutorialspoint;
  2. import java.util.List;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import com.tutorialspoint.StudentJDBCTemplate;
  6. public class MainApp {
  7. public static void main(String[] args) {
  8. ApplicationContext context =
  9. new ClassPathXmlApplicationContext("Beans.xml");
  10. StudentJDBCTemplate studentJDBCTemplate =
  11. (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
  12. System.out.println("------Records Creation--------" );
  13. studentJDBCTemplate.create("Zara", 11);
  14. studentJDBCTemplate.create("Nuha", 2);
  15. studentJDBCTemplate.create("Ayan", 15);
  16. System.out.println("------Listing Multiple Records--------" );
  17. List<Student> students = studentJDBCTemplate.listStudents();
  18. for (Student record : students) {
  19. System.out.print("ID : " + record.getId() );
  20. System.out.print(", Name : " + record.getName() );
  21. System.out.println(", Age : " + record.getAge());
  22. }
  23. System.out.println("----Updating Record with ID = 2 -----" );
  24. studentJDBCTemplate.update(2, 20);
  25. System.out.println("----Listing Record with ID = 2 -----" );
  26. Student student = studentJDBCTemplate.getStudent(2);
  27. System.out.print("ID : " + student.getId() );
  28. System.out.print(", Name : " + student.getName() );
  29. System.out.println(", Age : " + student.getAge());
  30. }
  31. }

下述是配置文件 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. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
  6.  
  7. <!-- Initialization for data source -->
  8. <bean id="dataSource"
  9. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  10. <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  11. <property name="url" value="jdbc:mysql://localhost:3306/TEST"/>
  12. <property name="username" value="root"/>
  13. <property name="password" value="password"/>
  14. </bean>
  15.  
  16. <!-- Definition for studentJDBCTemplate bean -->
  17. <bean id="studentJDBCTemplate"
  18. class="com.tutorialspoint.StudentJDBCTemplate">
  19. <property name="dataSource" ref="dataSource" />
  20. </bean>
  21.  
  22. </beans>

当你完成创建源和 bean 配置文件后,运行应用程序。如果你的应用程序一切运行顺利的话,将会输出如下所示的消息:

  1. ------Records Creation--------
  2. Created Record Name = Zara Age = 11
  3. Created Record Name = Nuha Age = 2
  4. Created Record Name = Ayan Age = 15
  5. ------Listing Multiple Records--------
  6. ID : 1, Name : Zara, Age : 11
  7. ID : 2, Name : Nuha, Age : 2
  8. ID : 3, Name : Ayan, Age : 15
  9. ----Updating Record with ID = 2 -----
  10. Updated Record with ID = 2
  11. ----Listing Record with ID = 2 -----
  12. ID : 2, Name : Nuha, Age : 20

你可以尝试自己删除在我的例子中我没有用到的操作,但是现在你有一个基于 Spring JDBC 框架的工作应用程序,你可以根据你的项目需求来扩展这个框架,添加复杂的功能。还有其他方法来访问你使用 NamedParameterJdbcTemplateSimpleJdbcTemplate 类的数据库,所以如果你有兴趣学习这些类的话,那么你可以查看 Spring 框架的参考手册。

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号