1. ORMフレームワークの役割
データアクセス層では、クライアントからのリクエストを解析し、接続プール経由でSQLに変換、適切なストレージエンジンで実行します。
1.1 JDBCの基本
JDBCはデータベースアクセスの標準インタフェースであり、アプリケーションとデータベースの橋渡しを担います。
1.2 ORMの必要性
直接のSQL操作はパフォーマンスに課題をもたらすため、MyBatisやGPAなどのORMフレームワークが導入されます。
2. MyBatis Plusの実装例
2.1 プロジェクト構成
Maven依存関係の設定例(変更点:グループID、バージョン番号、構成名を再定義)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.library</groupId>
<artifactId>library-system</artifactId>
<version>2.0.0</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<druid.version>1.2.20</druid.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.15</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.7</version>
</dependency>
</dependencies>
</project>
2.2 データソース設定
application.propertiesの例(URLやパラメータを変更)
spring:
datasource:
druid:
url: jdbc:mysql://db-server:3306/library_db?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: library_user
password: secure_password
driver-class-name: com.mysql.cj.jdbc.Driver
initial-size: 3
max-active: 30
min-idle: 3
max-wait: 5000
validation-query: SELECT 1
2.3 分ページ処理の実装
分ページインターセプターの設定
@Configuration
public class PaginationConfig {
@Bean
public MybatisPlusInterceptor paginationInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
2.4 クエリ実行例
Lambdaクエリの実装例(メソッド名・パラメータを変更)
public IPage<LibraryItem> getItemsByCategory(String category, int page, int size) {
IPage<LibraryItem> pageRequest = new Page<>(page, size);
LambdaQueryWrapper<LibraryItem> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(LibraryItem::getCategory, category)
.ge(LibraryItem::getPrice, 1000);
return itemMapper.selectPage(pageRequest, wrapper);
}
3. ストレージエンジンの比較
主なエンジンの特徴と適応ケース
| エンジン | トランザクション | ロックレベル | 最適ケース |
|---|---|---|---|
| InnoDB | サポート | 行ロック | 高並発書き込み |
| MyISAM | 非サポート | テーブルロック | 読み取り専用処理 |
| MEMORY | 非サポート | 行ロック | 一時データ処理 |
4. データアクセスのベストプラクティス
MyBatis Plusの注釈活用例
@TableName("library_items"): テーブル名の指定@TableId(type = IdType.AUTO): 自動増分キー@TableField(update = "version + 1"): バージョンアップ用更新
SQLインジェクション対策の重要性
- PrepareStatementを使用してパラメータ化
- 「#」によるパラメータ化が安全、「$」は推奨されない