Spring - JDBC Framework Overview
JdbcTemplate Class
Configuring Data Source
CREATE TABLE Student( ID INT NOT NULL AUTO_INCREMENT, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, PRIMARY KEY (ID) );
****Ubuntu:/usr$ sudo mysql -uroot -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 40
Server version: 5.5.43-MariaDB-1ubuntu0.14.04.2 (Ubuntu)
Copyright (c) 2000, 2015, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| TestDB |
| mysql |
| performance_schema |
+--------------------+
4 rows in set (0.02 sec)
MariaDB [(none)]> use TestDB
Database changed
MariaDB [TestDB]> show tables
-> ;
Empty set (0.00 sec)
MariaDB [TestDB]> CREATE TABLE Student(
-> ID INT NOT NULL AUTO_INCREMENT,
-> NAME VARCHAR(20) NOT NULL,
-> AGE INT NOT NULL,
-> PRIMARY KEY(ID)
-> );
Query OK, 0 rows affected (0.04 sec)
MariaDB [TestDB]> show tables
-> ;
+------------------+
| Tables_in_TestDB |
+------------------+
| Student |
+------------------+
1 row in set (0.00 sec)
MariaDB [TestDB]>
<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="password"/> </bean>
Data Access Object (DAO)
DAO는 database interaction(상호작용)을 위해 보통 사용되는 data access object을 의미한다. DAO는 database에 data를 읽고 쓰기 위한 의미를 제공하기 위해 존재하고 나머지 프로그램이 이에 접근할 interface를 통해 이 기능을 노출시킨다.
DAO는 Spring이 JDBC, Hibernete, JPA, JDO같은 data access 기술과 함께 작동되도록 지원한다.
Executing SQL statements
SQL과 JdbcTemplate를 사용하여 database상의 table의 CRUD(Create, Read, Update, Delete) 동작을 어떻게 수행하는지 보자.
Integer를 위한 Query:
String SQL = "select count(*) from Student"; int rowCount = jdbcTemplateObject.queryForInt( SQL );
long을 위한 Query:
String SQL = "select count(*) from Student"; long rowCount = jdbcTemplateObject.queryForLong( SQL );
bind변수(variable)을 사용하는 간단한 query:
String SQL = "select age from Student where id = ?"; int age = jdbcTemplateObject.queryForInt(SQL, new Object[]{10});
String을 위한 Query:
String SQL = "select name from Student where id = ?"; String name = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, String.class);
Query를 수행하고 객체(object)를 반환:
String SQL = "select * from Student where id = ?"; Student student = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, new StudentMapper()); 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; } }
Query를 수행하고 다중 객체를 반환:
String SQL = "select * from Student"; List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper()); 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; } }
table에 row insert:
String SQL = "insert into Student (name, age) values (?, ?)"; jdbcTemplateObject.update( SQL, new Object[]{"Zara", 11} );
table에 row update:
String SQL = "update Student set name = ? where id = ?"; jdbcTemplateObject.update( SQL, new Object[]{"Zara", 10} );
table에서 row 삭제
String SQL = "delete Student where id = ?"; jdbcTemplateObject.update( SQL, new Object[]{20} );
Executing DDL Statements
임의의 SQL문이나 DDL문을 실행하기 위해 JdbcTemplate에서 execute()함수를 사용할 수 있다. 아래는 테이블을 생성하기 위한 CREATE문을 사용한 예제이다.
String SQL = "CREATE TABLE Student( " + "ID INT NOT NULL AUTO_INCREMENT, " + "NAME VARCHAR(20) NOT NULL, " + "AGE INT NOT NULL, " + "PRIMARY KEY (ID));" jdbcTemplateObject.execute( SQL );
Spring JDBC Framework Examples:
위의 개념을 기본으로 하여 Spring의 JDBC framework의 사용을 이해하는 것을 도울 몇가지 중요한 예를 보자.
S.N. | Example & Description |
---|---|
1 | Spring JDBC Example 이 예제는 간단한 JDBC기반 Spring 프을 작성하는 법을 설명할 것이다. |
2 | SQL Stored Procedure in Spring Spring에서 JDBC를 사용하는 동안 어떻게 SQL stored procedure를 호출하는지를 배운다. |
(--> 예전에 셋팅해 놓고 방치해놨던 MariaDB가 정상적으로 돌아가는지 등 이것저것 점검하다 보니 오늘은 진도를 거의 못나갔다.. 그래도 이것을 점검해 놔야 다음 예제를 실행해 볼 수 있으니 어쩔수 없는 상황임에는 틀림없다. 큰 플젝이나 작은 플젝이나 환경셋팅이 초반 시간을 많이 잡아먹는건 똑같은 것 같다..ㅎㅎ)