Spring学習ノート(四):Springデータベースプログラミング
23513 ワード
SpringはデータベースプログラミングのためにJDBCテンプレートを提供し、多くのコードを簡略化することができますが、実際にはあまり使われていないので、理解だけをします.
全章転送ゲート:Spring学習ノート(一):Spring IoC容器Spring学習ノート(二):Spring Bern Spring学習ノート(三):Springはカット面Spring学習ノート(四):SpringデータベースプログラミングSpring学習ノート(五):Spring事务管理
従来のJDBCコード
まずは伝統的なJDBC操作をまとめます.
データベース操作をテストするために、まずデータベースにテーブルを挿入し、データを追加します.
MAVEN項目を作成し、JDBC依存を追加します.
伝統的なJDBCを最適化する
重複したテンプレートコードを持ち出してツールクラスを作成できます.
データベースリソースの設定
JDBCの問題を解決するために、Springは自分の解決策を提供しています.それはJdbcTemplateテンプレートですが、まずはデータベースリソースの配置方法を確認してください.
簡単なデータベースの設定
Springは簡単なデータベース構成org.springframewark.jdbc.datasource.SimpleDriverDataSourceを提供しています.データベース接続プールをサポートしないので、簡単なテストに使われます.
データソースがTomcatなどのサーバーに配置されている場合、JNDIでデータソースを配置する必要があります.TomcatにJNDIがjdbc/springdbのデータソースを配置していると仮定すると、Webエンジニアリングでは次のように構成されている.
JdbcTemplateはSpringがJDBCコードの暴走に対して提供したソリューションですが、厳密には成功したとは言えません.しかし、Springフレームワークの主導的な考えの一つを体現しています.常用技術にテンプレート化プログラミングを提供し、開発者の仕事量を減らすことができます.
まずプロジェクトのために完全なプロファイルspring-cfg.xmlを追加します.DBCPデータベース接続池を使用していますので、DBCP依存を追加する必要があります.
増加、削除、変更、検索はすべてJdbcTemplateを使うことができます.
MyBatis-pringプロジェクト
MyBatis-pringはMyBatisコードをSpringにシームレスに統合するのを助けます.
前のデータソースを使ってプロジェクトを作成し、Maven依存を追加します.
Sql Session FactoryBenを配置
MyBatisでは、Sql Session FactoryはSql Sessionのベースを生成し、構成が非常に重要です.MyBatis-pringプロジェクトではSql Session FactoryBenがSql Session Factoryの構成をサポートします.
XMLプロファイルにSql Session FactoryBeanを配置します.
Sql Session Templateコンポーネント
Sql Session Templateは必須のコンポーネントではなく、広く使われているわけではないですが、自分の長所もあります.まず、スレッドは安全で、その次に一連の添削機能を提供します.
まずそれを配置するには、パラメータの構造方法を参照する必要があります.
注意すべき点は、Sql Session FactoryとSql Session Templateを同時に配置した場合、Sql Session Templateの方が優先度が高いことです.
Mapper FactoryBenの設定
MyBatis-pringはまた、Mapper FactoryBernを仲介クラスとして提供しており、それを配置することでMapperインターフェースを実現しています.
マップファイルが多い場合は、一つの構成が氾濫するため、クラスMapperScanner Configrerを提供し、スキャンによって配置します.
まずMapperScanner Configrerの主な構成を紹介します. basePackage:スキャンが必要なカバンは、カンマで区切られています. annotationClass:スキャンが注釈された識別されたクラスを表し、開発方式を提案し、一般的に注釈@Repositoryを使用してデータアクセス層を識別する. Sql Session BeanName:Springで定義されているSql FactoryBeanのBean名を指定します. markerInterface:どのインターフェースが実装されているかを指定すると、Mapperと見なされ、共通インターフェースを提供する必要があります. 共通の拡張インターフェースを追加するという2つの構成が見られますが、いつも一つのインターフェースを拡張するとおかしくなります.普通は注釈@Repositionyを使って対応するMapperを表示します.
RoleMapperを修正します.
全章転送ゲート:Spring学習ノート(一):Spring IoC容器Spring学習ノート(二):Spring Bern Spring学習ノート(三):Springはカット面Spring学習ノート(四):SpringデータベースプログラミングSpring学習ノート(五):Spring事务管理
従来のJDBCコード
まずは伝統的なJDBC操作をまとめます.
データベース操作をテストするために、まずデータベースにテーブルを挿入し、データを追加します.
create table t_role(
id int auto_increment primary key,
role_name varchar(20),
note varchar(50)
);
insert into t_role(role_name, note) values('warrior','Warriors can use all kinds of weapons skillfully');
伝統JDBC回顧MAVEN項目を作成し、JDBC依存を追加します.
mysql
mysql-connector-java
5.1.25
データベース内のテーブルに対応するRoleエンティティクラスを作成します.package com.wyk.springdb.domain;
public class Role {
private Long id;
private String roleName;
private String note;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
そして伝統的なJDBCクエリコードを作成します.package com.wyk.springdb.db;
import com.wyk.springdb.domain.Role;
import java.sql.*;
public class DbOPeration {
public Role getRole(Long id) {
Role role = null;
// jdbc
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//
Class.forName("com.mysql.jdbc.Driver");
//
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/springstudy",
"root", "wanyunkai123");
// SQL
ps = con.prepareStatement("select id, role_name, note from t_role where id = ?");
//
ps.setLong(1, id);
// SQL
rs = ps.executeQuery();
// POJO
while(rs.next()) {
role = new Role();
role.setId(rs.getLong(1));
role.setRoleName(rs.getString(2));
role.setNote(rs.getString(3));
}
} catch (ClassNotFoundException | SQLException e) {
//
e.printStackTrace();
} finally {
//
try {
if(rs != null && (!rs.isClosed())) {
rs.close();
}
} catch(SQLException e) {
e.printStackTrace();
}
try {
if(ps != null && !ps.isClosed()) {
ps.close();
}
} catch(SQLException e) {
e.printStackTrace();
}
try {
if(con != null && !con.isClosed()) {
con.close();
}
} catch(SQLException e) {
e.printStackTrace();
}
}
return role;
}
}
コードを作成してテストします.public class JdbcTest {
public static void main(String[] args) {
DbOPeration operation = new DbOPeration();
Role role = operation.getRole(1L);
System.out.println("{id: " + role.getId() + ", role_name: "
+ role.getRoleName() + ", note: " + role.getNote() + "}");
}
}
実行プログラムは結果を調べられますが、簡単な検索だけでコードも複雑です.try...catch...finally...文も多く含まれています.伝統的なJDBCを最適化する
重複したテンプレートコードを持ち出してツールクラスを作成できます.
package com.wyk.springdb.util;
import org.omg.CORBA.OBJECT_NOT_EXIST;
import java.sql.*;
public class DBUtil {
static String ip = "127.0.0.1";
static int port = 3306;
static String database = "springstudy";
static String encoding = "UTF-8";
static String username = "root";
static String password = "wanyunkai123";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//
public static Connection getConnection() throws SQLException {
String url = String.format("jdbc:mysql://%s:%d/%s?characterEncoding=%s",
ip, port, database, encoding);
return DriverManager.getConnection(url, username, password);
}
public static void closeResource(Connection conn, Statement st, ResultSet rs) {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
このようにしてクエリークラスを変更できます.package com.wyk.springdb.db;
import com.wyk.springdb.domain.Role;
import com.wyk.springdb.util.DBUtil;
import java.sql.*;
public class DbOPeration2 {
public Role getRole(Long id) {
Role role = null;
// jdbc
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DBUtil.getConnection();
// SQL
ps = con.prepareStatement("select id, role_name, note from t_role where id = ?");
//
ps.setLong(1, id);
// SQL
rs = ps.executeQuery();
// POJO
while(rs.next()) {
role = new Role();
role.setId(rs.getLong(1));
role.setRoleName(rs.getString(2));
role.setNote(rs.getString(3));
}
} catch (SQLException e) {
//
e.printStackTrace();
} finally {
DBUtil.closeResource(con, ps, rs);
}
return role;
}
}
最適化はできますが、伝統的なJDBCはまだ複雑すぎます.データベースリソースの設定
JDBCの問題を解決するために、Springは自分の解決策を提供しています.それはJdbcTemplateテンプレートですが、まずはデータベースリソースの配置方法を確認してください.
簡単なデータベースの設定
Springは簡単なデータベース構成org.springframewark.jdbc.datasource.SimpleDriverDataSourceを提供しています.データベース接続プールをサポートしないので、簡単なテストに使われます.
###
, DBCP 。
```xml
JNDIデータベース接続池を使うデータソースがTomcatなどのサーバーに配置されている場合、JNDIでデータソースを配置する必要があります.TomcatにJNDIがjdbc/springdbのデータソースを配置していると仮定すると、Webエンジニアリングでは次のように構成されている.
JdbcTemplateJdbcTemplateはSpringがJDBCコードの暴走に対して提供したソリューションですが、厳密には成功したとは言えません.しかし、Springフレームワークの主導的な考えの一つを体現しています.常用技術にテンプレート化プログラミングを提供し、開発者の仕事量を減らすことができます.
まずプロジェクトのために完全なプロファイルspring-cfg.xmlを追加します.DBCPデータベース接続池を使用していますので、DBCP依存を追加する必要があります.
データベース操作のテストクラスを追加します.package com.wyk.springdb.test;
import com.mysql.jdbc.JDBC4CallableStatement;
import com.wyk.springdb.domain.Role;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcTempLateTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-cfg.xml");
JdbcTemplate jdbcTemplate = ctx.getBean(JdbcTemplate.class);
Long id = 1L;
String sql = "select id, role_name, note from t_role where id = " + id;
Role role = jdbcTemplate.queryForObject(sql, new RowMapper() {
public Role mapRow(ResultSet rs, int i) throws SQLException {
Role result = new Role();
result.setId(rs.getLong("id"));
result.setRoleName(rs.getString("role_name"));
result.setNote(rs.getString("note"));
return result;
}
});
System.out.println("{id: " + role.getId() + ", role_name: "
+ role.getRoleName() + ", note: " + role.getNote() + "}");
}
}
クエリが成功しました.コードには匿名クラスが使用されています.Java 8はLambada表現を使用することもできます.増加、削除、変更、検索はすべてJdbcTemplateを使うことができます.
public class JdbcOperation {
public int insertRole(JdbcTemplate jdbcTemplate) {
String roleName = "role_name_1";
String note = "note_1";
String sql = "insert into t_role(role_name, note) values(?, ?)";
return jdbcTemplate.update(sql, roleName, note);
}
public int deleteRole(JdbcTemplate jdbcTemplate, Long id) {
String sql = "delete from t_role where id=?";
return jdbcTemplate.update(sql, id);
}
public int updateRole(JdbcTemplate jdbcTemplate, Role role) {
String sql = "update t_role set role_name=?, note=? where id=?";
return jdbcTemplate.update(sql, role.getRoleName(), role.getNote(), role.getId());
}
public List findRole(JdbcTemplate jdbcTemplate, String roleName) {
String sql = "select id, role_name, note from t_role where role_name like concat('%', ?, '%')";
Object[] params = {roleName};
List list = jdbcTemplate.query(sql, params, (ResultSet rs, int rowNum) -> {
Role result = new Role();
result.setId(rs.getLong("id"));
result.setRoleName(rs.getString("role_name"));
result.setNote(rs.getString("note"));
return result;
});
return list;
}
}
複数のSQL文を実行する必要があるならば、Connection CallbackやSttement Callbackなどのインターフェースを転送してフィードバックすることができます.MyBatis-pringプロジェクト
MyBatis-pringはMyBatisコードをSpringにシームレスに統合するのを助けます.
前のデータソースを使ってプロジェクトを作成し、Maven依存を追加します.
4.0.0
com.wyk
springmybatisdemo
1.0-SNAPSHOT
4.3.2.RELEASE
3.4.0
org.springframework
spring-core
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-aop
${spring.version}
org.springframework
spring-context-support
${spring.version}
org.mybatis
mybatis
${mybatis.version}
org.mybatis
mybatis-spring
1.3.0
mysql
mysql-connector-java
5.1.25
commons-dbcp
commons-dbcp
1.4
log4j
log4j
1.2.17
src/main/java
**/*.xml
true
エンティティクラスRoleを作成し、データソース構成を追加し、前述のように、ここではもはや説明しない.Sql Session FactoryBenを配置
MyBatisでは、Sql Session FactoryはSql Sessionのベースを生成し、構成が非常に重要です.MyBatis-pringプロジェクトではSql Session FactoryBenがSql Session Factoryの構成をサポートします.
XMLプロファイルにSql Session FactoryBeanを配置します.
ここにMyBatisのプロファイルsql MapConfig.xmlを紹介します.内容は以下の通りです.
次に、MyBatisのマッピングインターフェースRoleMapper.javaとマッピングファイルRoleMapper.xmlを作成します.package com.wyk.springmybatisdemo.mapper;
import com.wyk.springmybatisdemo.domain.Role;
import org.apache.ibatis.annotations.Param;
public interface RoleMapper {
public int insertRole(Role role);
public Role getRole(@Param("id") Long id);
public int updateRole(Role role);
public int deleteRole(@Param("id") Long id);
}
insert into t_role(role_name, note) values (#{roleName}, #{note})
delete from t_role where id=#{id}
update t_role
set role_name = #{roleName},
note = #{note}
where id = #{id}
ここに来て基本的にMyBatisフレームのコードを完成しました.Sql Session Templateコンポーネント
Sql Session Templateは必須のコンポーネントではなく、広く使われているわけではないですが、自分の長所もあります.まず、スレッドは安全で、その次に一連の添削機能を提供します.
まずそれを配置するには、パラメータの構造方法を参照する必要があります.
そして使えます.public class SqlSessionTemplateTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-cfg.xml");
SqlSessionTemplate sqlSessionTemplate = ctx.getBean(SqlSessionTemplate.class);
Role role = new Role();
role.setRoleName("gjj");
role.setNote("sqlSessionTempalte_note");
sqlSessionTemplate.insert("com.wyk.springmybatisdemo.mapper.RoleMapper.insertRole", role);
Long id = role.getId();
sqlSessionTemplate.selectOne("com.wyk.springmybatisdemo.mapper.RoleMapper.getRole", id);
role.setNote("update_sqlSessionTemplate");
sqlSessionTemplate.update("com.wyk.springmybatisdemo.mapper.RoleMapper.updateRole", role);
sqlSessionTemplate.delete("com.wyk.springmybatisdemo.mapper.RoleMapper.deleteRole", id);
}
}
sql Session Templateでは、どのSQLを実行するかを文字列で示す必要があり、IDEはコード論理をチェックできないので、次第に人々に捨てられていくことが見られます.注意すべき点は、Sql Session FactoryとSql Session Templateを同時に配置した場合、Sql Session Templateの方が優先度が高いことです.
Mapper FactoryBenの設定
MyBatis-pringはまた、Mapper FactoryBernを仲介クラスとして提供しており、それを配置することでMapperインターフェースを実現しています.
このようにして、下のコードでマッパーを取得することができます.RoleMapper roleMapper = ctx.getBean(RoleMapper.class);
Mapper Scanner Configrerの設定マップファイルが多い場合は、一つの構成が氾濫するため、クラスMapperScanner Configrerを提供し、スキャンによって配置します.
まずMapperScanner Configrerの主な構成を紹介します.
RoleMapperを修正します.
package com.wyk.springmybatisdemo.mapper;
import com.wyk.springmybatisdemo.domain.Role;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface RoleMapper {
public int insertRole(Role role);
public Role getRole(@Param("id") Long id);
public int updateRole(Role role);
public int deleteRole(@Param("id") Long id);
}
設定ファイルにプロファイルを追加します.
テストコードを追加して、テスト結果を確認します.package com.wyk.springmybatisdemo.mainApp;
import com.wyk.springmybatisdemo.domain.Role;
import com.wyk.springmybatisdemo.mapper.RoleMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringMybatisTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-cfg.xml");
RoleMapper roleMapper = ctx.getBean(RoleMapper.class);
Role role = new Role();
role.setRoleName("gjj1");
role.setNote("gjj_note");
roleMapper.insertRole(role);
Long id = role.getId();
System.out.println(id);
roleMapper.getRole(id);
role.setNote("update_note");
roleMapper.updateRole(role);
roleMapper.deleteRole(id);
}
}