Spring JDBC - Richiamo di una funzione memorizzata

L'esempio seguente dimostrerà come chiamare una funzione memorizzata utilizzando Spring JDBC. Leggeremo uno dei record disponibili nella Student Table chiamando una funzione memorizzata. Passeremo un ID e riceveremo il nome di uno studente.

Sintassi

SimpleJdbcCall jdbcCall = new 
   SimpleJdbcCall(dataSource).withFunctionName("get_student_name");

SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id);
String name = jdbcCall.executeFunction(String.class, in);

Student student = new Student();
student.setId(id);
student.setName(name);

Dove,

  • in - Oggetto SqlParameterSource per passare un parametro a una funzione memorizzata.

  • jdbcCall - Oggetto SimpleJdbcCall per rappresentare una funzione memorizzata.

  • jdbcTemplateObject - Oggetto StudentJDBCTemplate per richiamare la funzione memorizzata dal database.

  • student - Oggetto studente.

Il SimpleJdbcCallclass può essere utilizzata per chiamare una funzione memorizzata con il parametro IN e un valore di ritorno. È possibile utilizzare questo approccio mentre si lavora con uno degli RDBMS come Apache Derby, DB2, MySQL, Microsoft SQL Server, Oracle e Sybase.

Per comprendere l'approccio, considera la seguente procedura memorizzata MySQL, che prende l'ID dello studente e restituisce il nome dello studente corrispondente. Quindi cerchiamo di creare questa funzione memorizzata nel tuo database TEST utilizzando il prompt dei comandi di MySQL -

DELIMITER $$

DROP FUNCTION IF EXISTS `TEST`.`get_student_name` $$
CREATE FUNCTION `get_student_name` (in_id INTEGER)
RETURNS varchar(200)
BEGIN
DECLARE out_name VARCHAR(200);
   SELECT name
   INTO out_name
   FROM Student where id = in_id;

RETURN out_name;

DELIMITER ;

Per comprendere i concetti sopra menzionati relativi a Spring JDBC, scriviamo un esempio che chiamerà una funzione memorizzata. Per scrivere il nostro esempio, disponiamo di un IDE Eclipse funzionante e utilizziamo i seguenti passaggi per creare un'applicazione Spring.

Passo Descrizione
1 Aggiorna il progetto Studente creato nel capitolo Spring JDBC - Prima applicazione .
2 Aggiorna la configurazione del bean ed esegui l'applicazione come spiegato di seguito.

Di seguito è riportato il contenuto del file di interfaccia dell'oggetto di accesso ai dati 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);  
}

Di seguito è riportato il contenuto del file Student.java file.

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;
   }
}

Di seguito è riportato il contenuto del file StudentMapper.java file.

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;
   }
}

Di seguito è riportato il file della classe di implementazione StudentJDBCTemplate.java per l'interfaccia DAO definita StudentDAO.

package com.tutorialspoint;

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

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;

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) {
      SimpleJdbcCall jdbcCall = new 
         SimpleJdbcCall(dataSource).withFunctionName("get_student_name");
	   
      SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id);
      String name = jdbcCall.executeFunction(String.class, in);
      Student student = new Student();
      student.setId(id);
      student.setName(name);
      return student;      
   }
}

Il codice che scrivi per l'esecuzione della chiamata implica la creazione di un SqlParameterSource contenente il parametro IN. È importante far corrispondere il nome fornito per il valore di input con quello del nome del parametro dichiarato nella funzione memorizzata. Il metodo executeFunction accetta i parametri IN e restituisce una stringa come specificato nella funzione memorizzata.

Di seguito è riportato il contenuto del file MainApp.java file

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() );
   }
}

Di seguito è riportato il file di configurazione 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>

Una volta terminata la creazione dei file di configurazione dei bean e dei sorgenti, eseguiamo l'applicazione. Se tutto va bene con la tua applicazione, verrà stampato il seguente messaggio.

ID : 1, Name : Zara