English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Esempio di PreparedStatement in Spring JdbcTemplate

Grazie alla classe execute()Metodo, possiamo eseguire query parametrizzate utilizzando Spring JdbcTemplate. Per utilizzare query parametrizzate, passiamo PreparedStatementCallback un'istanza.

La sintassi del metodo execute per utilizzare query parametrizzate

public T execute(String sql,PreparedStatementCallback<T>);

Interfaccia PreparedStatementCallback

Gestisce i parametri di input e i risultati di output. In questo caso, non dovete preoccuparvi delle virgolette singole e doppie.

Metodo dell'interfaccia PreparedStatementCallback

Ha un solo metodo doInPreparedStatement. La sintassi di questo metodo è la seguente:

public T doInPreparedStatement(PreparedStatement ps)throws SQLException, DataAccessException

Esempio di utilizzo di PreparedStatement in Spring

Supponiamo che abbiate creato la seguente tabella nel database Oracle10g.

create table employee(
id number(10),
name varchar2(100),
salary number(10)
);

Employee.java

Questa classe contiene 3 attributi con costruttore, setter e getter.

package com.w3codebox;
public class Employee {
private int id;
private String name;
private float salary;
//costruttori senza argomenti e parametrizzati
//getter e setter
}

EmployeeDao.java

Esso contiene un attributo jdbcTemplate e un metodo saveEmployeeByPreparedStatement. È necessario comprendere il concetto di classe anonima per comprendere il codice di questo metodo.

package com.w3codebox;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
}
public boolean saveEmployeeByPreparedStatement(final Employee e){
    String query = "insert into employee values(?,?,?)";
    return jdbcTemplate.execute(query, new PreparedStatementCallback<Boolean>(){
    @Override
    public boolean doInPreparedStatement(PreparedStatement ps)
            throws SQLException, DataAccessException {
        ps.setInt(1, e.getId());
        ps.setString(2, e.getName());
        ps.setFloat(3, e.getSalary());
        return ps.execute();
    }
    });
}
}

applicationContext.xml

DriverManagerDataSource usato per contenere informazioni sul database, ad esempio il nome della classe del driver, l'URL di connessione, il nome utente e la password.

Nella classe JdbcTemplate di tipo DriverManagerDataSource c'è un metodo chiamato datasource L'attributo. Pertanto, dobbiamo fornire un riferimento all'oggetto DriverManagerDataSource per l'attributo di sorgente dati nella classe JdbcTemplate.

In questo articolo, abbiamo utilizzato l'oggetto JdbcTemplate nella classe EmployeeDao, quindi lo abbiamo trasmesso tramite il metodo setter, ma puoi anche utilizzare il costruttore.

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="oracle" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.w3codebox.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>

Test.java

Questa classe recupera il Bean dal file applicationContext.xml e chiama il metodo saveEmployeeByPreparedStatement().

package com.w3codebox;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
    ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
    EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
    dao.saveEmployeeByPreparedStatement(new Employee(108,"Amit",35000));
}
}