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

Spring JdbcTemplate에서 PreparedStatement의 예제

JdbcTemplate 클래스의 execute()메서드를 사용하면 Spring JdbcTemplate를 통해 파라미터화된 쿼리를 실행할 수 있습니다. 파라미터화된 쿼리를 사용하려면 execute 메서드에 PreparedStatementCallback 의 인스턴스를 사용합니다.

execute 메서드의 문법은 파라미터화된 쿼리를 사용하여

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

PreparedStatementCallback 인터페이스

입력 파라미터와 출력 결과를 처리합니다. 이 경우, 쌍따옴표와 일반따옴표에 대해 신경 쓰지 않아도 됩니다.

PreparedStatementCallback 인터페이스의 메서드

doInPreparedStatement 메서드가 하나만 있습니다. 이 메서드의 문법은 다음과 같습니다:

public T doInPreparedStatement(PreparedStatement ps)throws SQLException, DataAccessException

Spring에서 PreparedStatement의 예제

Oracle에서 이미 설치되어 있다고 가정합니다.10g 데이터베이스에서 다음 테이블을 생성했습니다.

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

Employee.java

이 클래스는 다음을 포함하고 있습니다:3객체가 생성자, setter와 getter를 가지고 있습니다.

package com.w3codebox;
public class Employee {
private int id;
private String name;
private float salary;
//no-arg and parameterized constructors
//getters and setters
}

EmployeeDao.java

그것은 jdbcTemplate 속성과 saveEmployeeByPreparedStatement 메서드를 포함하고 있습니다. 이 메서드의 코드를 이해하기 위해서는 익명 클래스 개념을 이해해야 합니다.

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 데이터베이스에 대한 정보를 포함하는 데 사용됩니다. 예를 들어, 드라이버 클래스 이름, 연결 URL, 사용자 이름 및 비밀번호.

DriverManagerDataSource 타입의 JdbcTemplate 클래스에는 "}} datasource 의 속성을 사용하고 있습니다. 따라서 JdbcTemplate 클래스에서 DriverManagerDataSource 객체의 참조를 데이터 소스 속성에 제공해야 합니다.

여기서 우리는 EmployeeDao 클래스에서 JdbcTemplate 객체를 사용하고 있으며, 따라서 setter 메서드를 통해 전달했지만, 생성자를 사용할 수도 있습니다.

<?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

이 클래스는 applicationContext.xml 파일에서 Bean을 가져오고 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));
}
}