탑크리에듀교육센터(www.topcredu.co.kr)제공
스프링프레임워크 & 마이바티스(Spring Framework, MyBatis)
18번째 자료입니다. 참고하시어 많은 도움되셨길 바랍니다.
교육 및 수강문의/기타문의사항은 홈페이지(www.topcredu.co.kr)를 통하여 하실 수 있습니다.^^
1. 스프링프레임워크 & 마이바티스
(Spring Framework, MyBatis)
4-3-5. Spring JDBC에서 DB 접근하는 방법 – SqlUpdate
재사용 가능한 SQL Update 구문을 생성하며, 이를 위해 SqlUpdate 클래스를 상속받아서 구
현해야 한다.
SqlUpdate를 상속받은 하위 클래스의 생성자에서 SQL 쿼리 구문(DML : insert, update,
delete), 파라미터를 생성하고 compile() 메소드를 호출하여 컴파일 한다. 마지막으로 update()
메소드를 호출하여 해당 DML 쿼리를 실행한다.
public class PersonUpdate extends SqlUpdate {
public PersonUpdate(final DataSource ds) {
setDataSource(ds);//SqlUpdate의 메소드 호출
setSql("update Person set firstname = ?, lastname = ? where id = ?"); //SqlUpdate 메소드
호출
declareParameter(new SqlParameter(Types.VARCHAR)); //SqlUpdate 메소드
호출
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.INTRGER));
compile(); //SqlUpdate의 메소드 호출
}
//update 구문 실행
public int run(final Person person) {
Object[] params =
new Object[] {
person.getFirstName(),
person.getLastName(),
person.getId()};
return update(params);
2. }
}
public class PersonInsert extends SqlUpdate {
public PersonInsert(final DataSource ds) {
setDataSource(ds);
setSql("insert into Person(id, firstname, lastname) values(?, ?, ?)");
declareParameter(new SqlParameter(Types.INTEGER));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.VARCHAR));
compile();
}
// insert 구문 실행
public int run(final Person person) {
Object[] params = new Object[] { pserson.getId(),
person.getFirstName(),
person.getLastName()};
return update(params);
}
}
4-3-6. Spring JDBC에서 DB 접근하는 방법 – StoredProcedure
Spring JDBC의 StoredProcedure를 상속받아서 서버쪽의 저장함수나 프러시저에 접근 가능하
다.
[Emp.java]
package edu.onj.function2;
public class Emp {
private String empno;
private String ename;
private String sal;
public Emp() {}
public Emp(String empno, String ename, String sal) {
this.empno = empno;
this.ename = ename;
3. this.sal = sal;
}
public void setEmpno(String empno) {
this.empno = empno;
}
public void setEname(String ename) {
this.ename = ename;
}
public void setSal(String sal) {
this.sal = sal;
}
public String getEmpno() {
return empno;
public String getEname() {
return ename;
}
public String getSal() {
return sal;
}
}
[EmpDao.java]
package edu.onj.function2;
import java.util.List;
import javax.sql.DataSource;
public interface EmpDao {
public void setDataSource(DataSource ds);
public List<Emp> listEmp(Integer deptno);
}
[EmpMapper.java]
package edu.onj.function2;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class EmpMapper implements RowMapper<Emp> {
4. @Override
public Emp mapRow(ResultSet rs, int rowNum) throws SQLException {
Emp emp = new Emp();
emp.setEmpno(rs.getInt("empno"));
emp.setEname(rs.getString("ename"));
emp.setSal(rs.getInt("sal"));
return emp;
}
}
[EmpJDBCTemplate.java]
package edu.onj.function2;
import java.sql.Types;
import java.util.*;
import javax.sql.DataSource;
import oracle.jdbc.OracleTypes;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.StoredProcedure;
public class EmpJDBCTemplate extends StoredProcedure implements EmpDao {
private DataSource dataSource;
private static final String SQL = "getEmp";
public EmpJDBCTemplate(DataSource dataSource) {
super(dataSource, SQL);
setFunction(true);
declareParameter(new SqlOutParameter("emp_cursor", OracleTypes.CURSOR, new
EmpMapper()));
declareParameter(new SqlParameter("v_deptno", Types.INTEGER));
}
@Override
public List<Emp> listEmp(Integer deptno) {
Map<String, Object> resultSet = execute(deptno);
ArrayList<Emp> list = (ArrayList) resultSet.get("emp_cursor");
return list;
}
}
5. [JdbcClient.java]
package edu.onj.function2;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import onj.edu.jdbc1.Customer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class JdbcClient {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("jdbc2.xml");
EmpJDBCTemplate empJDBCTemplate
=(EmpJDBCTemplate)ctx.getBean("empJDBCTemplate");
ArrayList<Emp> list = new ArrayList<Emp>();
list = (ArrayList<Emp>) empJDBCTemplate.listEmp(20);
for (Emp emp:list){
System.out.println("empno --> "+emp.getEmpno()+"
ename --> "+emp.getEname()+" sal --> "+emp.getSal() );
}
}
}
[jdbc2.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.springfra
mework.org/schema/beans/spring-beans-4.2.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroymethod="close">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@192.168.0.27:1521:onj</value>
</property>
<property name="username">
<value>scott</value>
6. </property>
<property name="password">
<value>tiger</value>
</property>
</bean>
<bean id="empJDBCTemplate" class=" edu.onj.function2.EmpJDBCTemplate">
<constructor-arg ref="dataSource"/>
</bean>
</beans>
4-3-7. 오라클 시퀀스를 위한 DataFieldMaxValueIncrementer
DataFieldMaxValueIncrementer 인터페이스는 DB 테이블의 칼럼값을 MAX VALUE까지 자동증
분 하기 위한 용도로 사용되는 스프링의 인터페이스 이다. 오라클 DB라면 시퀀스를 스프링에
서 사용할 수 있게 해 준다.
인터페이스의 구조는 다음과 같다.
public interface DataFieldMaxValueIncrementer {
public int nextIntValue() throws DataAccessException;
public long nextLongValue() throws DataAccessException;
public String nextStringValue() throws DataAccessException;
}
스프링배치에서는 기본적으로 , Oracle, DB2, Derby, Hsql, Mysql, Postgres, MS-SQL Server,
Sybase 등의 주요 DB에 대한 DataFieldMaxValueIncrementer의 구현 클래스가 제공되고 있다.
사용절차는 다음과 같다.
1. Spring 설정파일에서 사용할 incrementer에 대해 정의
DB2는 SequenceMaxValueIncrementer, MySQL은 MySQLMaxValueIncrementer, PostgreSQL이라면
PostgreSQLSequenceMaxValueIncrementer, 오라클인 경우 OracleSequenceMaxValueIncrementer를
사용한다.
<bean id="incrementer"
class="org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
7. <property name="incrementerName">
<value>SEQ_SID</value> <!– 오라클에 만들어 놓은 시퀀스 이름 -
</property>
</bean>
2. Insert SQL문을 실행하는 부분에서 정의된 incrementer 사용
private DataFieldMaxValueIncrementer incrementer;
public void setIncrementer(DataFieldMaxValueIncrementer incrementer) {
this.incrementer = incrementer;
}
….
String strQuery = "INSERT INTO BOARD VALUES ( ?, ?, ?, ?, ?, sysdate) ";
int currentSid =new Integer(incrementer.nextIntValue());
사용 예제
[CustomerDao.java]
package onj.edu.jdbc1;
import java.util.List;
import javax.sql.DataSource;
public interface CustomerDAO {
public void setDataSource(DataSource ds);
public void create(Integer id, String name, Integer age);
public Customer getCustomer(Integer id);
public List<Customer> listCustomer();
public void delete(Integer id);
public void update(Integer id, Integer age);
}
[CustomerJDBCTemplate.java]
package onj.edu.jdbc1;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
8. import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer;
public class CustomerJDBCTemplate implements CustomerDAO {
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
private DataFieldMaxValueIncrementer incrementer;
public void setIncrementer(DataFieldMaxValueIncrementer incrementer) {
this.incrementer = incrementer;
}
public void setDataSource(DataSource ds) {
this.dataSource = ds;
this.jdbcTemplate = new JdbcTemplate(ds);
}
public void create(Integer id, String name, Integer age) {
String SQL = "insert into customer(id, name, age) values (?, ?, ?)";
jdbcTemplate.update(SQL, new Integer(incrementer.nextIntValue()), name, age);
System.out.println("<<<Customer insert ok ::: " + name + "," + age);
}
public Customer getCustomer(Integer id) {
String SQL = "select * from customer where id = ?";
Customer customer = jdbcTemplate.queryForObject(SQL, new Object[] { id }, new
CustomerMapper());
return customer;
}
public List<Customer> listCustomer() {
String SQL = "select * from customer";
List<Customer> customer = jdbcTemplate.query(SQL, new CustomerMapper());
return customer;
}
public void delete(Integer id) {
String SQL = "delete from customer where id = ?";
jdbcTemplate.update(SQL, id);
System.out.println("<<< customer delete ok ::: id = " + id);
9. }
public void update(Integer id, Integer age) {
String SQL = "update customer set age = ? where id = ?";
jdbcTemplate.update(SQL, age, id);
System.out.println("<<< customer update ok ::: id = " + id);
}
}
[CustomerMapper.java]
package onj.edu.jdbc1;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class CustomerMapper implements RowMapper<Customer>{
@Override
public Customer mapRow(ResultSet rs, int arg1) throws SQLException {
Customer customer = new Customer();
customer.setId(rs.getInt("id"));
customer.setName(rs.getString("name"));
customer.setAge(rs.getInt("age"));
return customer;
}
}
[jdbc3.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop