いっぽんの猟銃のむこうに (DAIZOじいさんとGun)

ヌルめの技術メモとか。フリーランスやってます (http://acez.jp/)

Spring 3で直接JDBCのConnectionを取得して実行

Spring3はSpringJDBCだのMyBatisやHibernate連携だの色々と充実してるんですが、場合によってはめんどくせえから直接SQL投げさせろやみたいな時もありますよね。(糞畜生)

そんな時はこんな感じで。(データソース関連の設定はできてる前提です)

ApplicationContext.xml

  <!-- jdbcTemplateを設定に追加 -->
  <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
      <property name="dataSource"><ref local="dataSource"/></property>
  </bean>

例えば単純に、JDBCのexecuteUpdate()使って更新用のSQLを投げるだけのクラス(SQLExecUtils)は以下のようになります。

SQLExecUtils.java

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Component;

@Component
public class SQLExecUtils {
	@Autowired
	JdbcTemplate jdbcTemplate;

	public void execUpdate(String sql) throws SQLException {
		Connection conn = DataSourceUtils.getConnection(jdbcTemplate
				.getDataSource());
		Statement stmt = conn.createStatement();
		stmt.executeUpdate(sql);
		conn.commit();
	}
}

あとは実行クラスで

	@Autowired
	SQLExecUtils sqlutils;

        // SQL実行
	sqlutils.execUpdate("INSERT INTO ....");

とかやるだけです。「いちいちO/Rマッパーとか使ってらんないわー」みたいなときにどうぞ。