Spring JDBC - Lớp StoredProcedure

Các org.springframework.jdbc.core.StoredProcedurelớp là lớp cha để trừu tượng hóa đối tượng của các thủ tục được lưu trữ RDBMS. Lớp này là trừu tượng và có mục đích là các lớp con sẽ cung cấp một phương thức đã định kiểu để gọi mà ủy quyền cho phương thức thực thi (java.lang.Object ...) được cung cấp. Thuộc tính SQL kế thừa là tên của thủ tục được lưu trữ trong RDBMS.

Khai báo lớp học

Sau đây là khai báo cho org.springframework.jdbc.core.StoredProcedure lớp học -

public abstract class StoredProcedure
   extends SqlCall

Ví dụ sau sẽ trình bày cách gọi một thủ tục được lưu trữ bằng Spring StoredProcedure. Chúng tôi sẽ đọc một trong các bản ghi có sẵn trong Bảng Sinh viên bằng cách gọi một thủ tục được lưu trữ. Chúng tôi sẽ chuyển id và nhận hồ sơ học sinh.

Cú pháp

class StudentProcedure extends StoredProcedure{
   public StudentProcedure(DataSource dataSource, String procedureName){
      super(dataSource,procedureName);
      declareParameter(new SqlParameter("in_id", Types.INTEGER));
      declareParameter(new SqlOutParameter("out_name", Types.VARCHAR));
      declareParameter(new SqlOutParameter("out_age", Types.INTEGER));
      compile();
   }
   public Student execute(Integer id){
      Map<String, Object> out = super.execute(id);
      Student student = new Student();
      student.setId(id);
      student.setName((String) out.get("out_name"));
      student.setAge((Integer) out.get("out_age"));
      return student;  	
   }
}

Ở đâu,

  • StoredProcedure - Đối tượng StoredProcedure để biểu diễn một thủ tục được lưu trữ.

  • StudentProcedure - Đối tượng StudentProcedure mở rộng StoredProcedure để khai báo biến đầu vào, đầu ra và ánh xạ kết quả cho đối tượng Student.

  • student - Đối tượng sinh viên.

Để hiểu các khái niệm được đề cập ở trên liên quan đến Spring JDBC, chúng ta hãy viết một ví dụ sẽ gọi một thủ tục được lưu trữ. Để viết ví dụ của chúng tôi, hãy để chúng tôi có một IDE Eclipse đang hoạt động tại chỗ và sử dụng các bước sau để tạo một ứng dụng Spring.

Bươc Sự miêu tả
1 Cập nhật dự án Sinh viên đã tạo theo chương Spring JDBC - Ứng dụng đầu tiên .
2 Cập nhật cấu hình bean và chạy ứng dụng như được giải thích bên dưới.

Sau đây là nội dung của tệp giao diện Đối tượng Truy cập Dữ liệu StudentDAO.java.

package com.tutorialspoint;

import java.util.List;
import javax.sql.DataSource;

public interface StudentDAO {
   /** 
      * This is the method to be used to initialize
      * database resources ie. connection.
   */
   public void setDataSource(DataSource ds);
   
   /** 
      * This is the method to be used to list down
      * a record from the Student table corresponding
      * to a passed student id.
   */
   public Student getStudent(Integer id);  
}

Sau đây là nội dung của Student.java tập tin.

package com.tutorialspoint;

public class Student {
   private Integer age;
   private String name;
   private Integer id;

   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      return age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public Integer getId() {
      return id;
   }
}

Sau đây là nội dung của StudentMapper.java tập tin.

package com.tutorialspoint;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class StudentMapper implements RowMapper<Student> {
   public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
      Student student = new Student();
      student.setId(rs.getInt("id"));
      student.setName(rs.getString("name"));
      student.setAge(rs.getInt("age"));
      return student;
   }
}

Sau đây là tệp lớp triển khai StudentJDBCTemplate.java cho giao diện DAO được định nghĩa StudentDAO.

package com.tutorialspoint;

import java.sql.Types;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.object.StoredProcedure;

public class StudentJDBCTemplate implements StudentDao {
   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject;
   
   public void setDataSource(DataSource dataSource) {
      this.dataSource = dataSource;
      this.jdbcTemplateObject = new JdbcTemplate(dataSource);
   }
   public Student getStudent(Integer id) {    
      StudentProcedure studentProcedure = new StudentProcedure(dataSource, "getRecord");
      return studentProcedure.execute(id);      
   }    
}
class StudentProcedure extends StoredProcedure{
   public StudentProcedure(DataSource dataSource, String procedureName) {
      super(dataSource,procedureName);
      declareParameter(new SqlParameter("in_id", Types.INTEGER));
      declareParameter(new SqlOutParameter("out_name", Types.VARCHAR));
      declareParameter(new SqlOutParameter("out_age", Types.INTEGER));
      compile();
   }
   public Student execute(Integer id){
      Map<String, Object> out = super.execute(id);
      Student student = new Student();
      student.setId(id);
      student.setName((String) out.get("out_name"));
      student.setAge((Integer) out.get("out_age"));
      return student;  	
   }
}

Mã bạn viết để thực hiện cuộc gọi liên quan đến việc tạo một SqlParameterSource chứa tham số IN. Điều quan trọng là phải khớp tên được cung cấp cho giá trị đầu vào với tên của tham số được khai báo trong thủ tục được lưu trữ. Phương thức thực thi nhận các tham số IN và trả về một Bản đồ có chứa bất kỳ tham số nào được khóa bằng tên như được chỉ định trong thủ tục được lưu trữ.

Sau đây là nội dung của MainApp.java tập tin.

package com.tutorialspoint;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.StudentJDBCTemplate;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      StudentJDBCTemplate studentJDBCTemplate = 
         (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
      
      Student student = studentJDBCTemplate.getStudent(1);
      System.out.print("ID : " + student.getId() );
      System.out.print(", Name : " + student.getName() );
      System.out.println(", Age : " + student.getAge()); 
   }
}

Sau đây là tệp cấu hình Beans.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

   <!-- Initialization for data source -->
   <bean id = "dataSource" 
      class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
      <property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
      <property name = "username" value = "root"/>
      <property name = "password" value = "admin"/>
   </bean>

   <!-- Definition for studentJDBCTemplate bean -->
   <bean id = "studentJDBCTemplate" 
      class = "com.tutorialspoint.StudentJDBCTemplate">
      <property name = "dataSource" ref = "dataSource" />    
   </bean>
      
</beans>

Khi bạn đã hoàn tất việc tạo các tệp cấu hình nguồn và bean, hãy để chúng tôi chạy ứng dụng. Nếu mọi thứ đều ổn với ứng dụng của bạn, nó sẽ in ra thông báo sau.

ID : 1, Name : Zara, Age : 10