本記事では、MyBatisフレームワークとOceanBaseデータベースを使用して、テーブルの作成、データの挿入、データのクエリなどの基本的な操作を実現するアプリケーションの構築方法を紹介します。
前提条件
- OceanBaseデータベースがインストール済みであること。
- JDK 1.8とMavenがインストール済みであること。
- IntelliJ IDEAがインストール済みであること。
説明
本ドキュメントでコードを実行するために使用したツールはIntelliJ IDEA 2021.3.2 (Community Edition)です。個人の好みに応じて、適切なツールを選択してサンプルコードを実行することもできます。
手順
説明
本記事で示す操作手順は、Windows環境に基づいています。他のOS環境やコンパイラを使用している場合は、操作手順が若干異なる場合があります。
- OceanBaseデータベースの接続文字列を取得します。
java-oceanbase-mybatisプロジェクトをIDEAにインポートします。java-oceanbase-mybatisプロジェクトのデータベース接続情報を修正します。java-oceanbase-mybatisプロジェクトを実行します。
ステップ1:OceanBaseデータベースの接続文字列を取得する
OceanBaseデータベースのデプロイ担当者または管理者から、該当するデータベース接続文字列を取得します。
obclient -hxx.xx.xx.xx -P2883 -uroot@sys#cluster -p**** -Aデプロイ済みのOceanBaseデータベースに基づいて、以下のURLに対応する情報を入力します。
説明
jdbc.propertiesファイルには、このURL情報が必要です。jdbc:oceanbase://host:port/schema_name?user=$user_name&password=$passwordパラメータ説明:
host:OceanBaseデータベースへの接続IPアドレス。ODP接続方式ではODPアドレスを使用し、直接接続方式ではOBServerノードのIPアドレスを使用します。port:OceanBaseデータベースへの接続ポート。ODP接続方式のデフォルトポートは2883で、ODPデプロイ時にカスタマイズ可能です。直接接続方式のデフォルトポートは2881で、OceanBaseデータベースのデプロイ時にカスタマイズ可能です。schema_name:アクセスするスキーマ名です。user_name:-uパラメータで指定し、形式はユーザー@テナント#クラスタ名またはユーザー名@SERVICE:サービス名です。ユーザー@テナント#クラスタ名の形式を使用する場合、デフォルトのテナントはsys、管理者ユーザーはrootです。データベースに直接接続する場合、クラスタ名を省略できますが、ODP接続の場合は入力する必要があります。password:アカウントのパスワードです。
その他のURLパラメータの詳細については、データベースURLを参照してください。
ステップ2:java-oceanbase-mybatis プロジェクトをIDEAにインポートする
IntelliJ IDEA を開き、File > Open... オプションを選択します。

表示された Open File or Project ウィンドウで、対応するプロジェクトファイルを選択し、OK をクリックしてプロジェクトファイルのインポートを完了します。
IntelliJ IDEAは、プロジェクト内のさまざまなファイルの種類を自動的に認識し、Project ツールウィンドウで、プロジェクトのディレクトリ構造、ファイルリスト、モジュールリスト、依存関係などの情報を確認できます。Project ツールウィンドウは通常、IntelliJ IDEA画面の左側にあり、デフォルトでは開いています。Project ツールウィンドウが閉じている場合は、メニューバーの View > Tool Windows > Project をクリックするか、ショートカットキー Alt + 1 を使用して再表示できます。
説明
IntelliJ IDEAでプロジェクトをインポートすると、IntelliJ IDEAはプロジェクト内のpom.xmlファイルを自動的に検出し、ファイルに記述されている依存関係に基づいて必要な依存ライブラリを自動的にダウンロードし、プロジェクトに追加します。
プロジェクトの状況を確認します。

ステップ3:java-oceanbase-mybatis プロジェクトのデータベース接続情報を修正する
ステップ1:OceanBaseデータベースの接続文字列を取得する の情報に基づいて、jdbc.properties ファイル内のデータベース接続情報を修正します。
例:
- データベースドライバーの名前:
com.oceanbase.jdbc.Driver - OBServerノードのIPアドレスは
10.10.10.1です。 - アクセスポートは2881を使用します。
- アクセスするスキーマ名は
testです。 - URLに追加の接続プロパティとして
useServerPrepStmts=true&rewriteBatchedStatements=trueを設定します。 - テナントの接続アカウントは
root@mysql001です。mysql001はOceanBaseデータベースで作成されたMySQLモードのユーザーテナントであり、rootはテナントmysql001のユーザー名です。 - パスワードは
******です。
サンプルコードは以下のとおりです:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:oceanbase://10.10.10.1:2881/sys?useServerPrepStmts=true&rewriteBatchedStatements=true
jdbc.username=root@mysql001
jdbc.password=******
ステップ4:java-oceanbase-mybatis プロジェクトを実行する
実行パス
- プロジェクト構造の src > test > java から
TestMybatis.javaファイルを見つけます。 - ツールメニューバーで 実行(U) > 実行 > TestMybatis を選択するか、右上の緑色の三角形を直接クリックして実行します。
- IDEAのコンソールを使用して、プロジェクトのログ情報と出力結果を確認します。
実行結果
testUserMapperメソッドを実行した出力結果は次のとおりです:User{id=2, name='update'} User{id=3, name='insert'} User{id=4, name='insert'} User{id=5, name='insert'} User{id=6, name='insert'} User{id=7, name='insert'} User{id=8, name='insert'} User{id=9, name='insert'} User{id=10, name='insert'} usersByPage = [User{id=5, name='insert'}, User{id=6, name='insert'}, User{id=7, name='insert'}]testSqlSessionメソッドを実行した出力結果は次のとおりです:User{id=2, name='update'} User{id=3, name='insert'} User{id=4, name='insert'} User{id=5, name='insert'} User{id=6, name='insert'} User{id=7, name='insert'} User{id=8, name='insert'} User{id=9, name='insert'} User{id=10, name='insert'}testAppMapperメソッドを実行した出力結果は次のとおりです:App{id=2, name='update'} App{id=3, name='insert3'} App{id=4, name='insert4'} App{id=5, name='insert5'} App{id=6, name='insert6'} App{id=7, name='insert7'} App{id=8, name='insert8'} App{id=9, name='insert9'} App{id=10, name='insert10'} pageList = Page{count=true, pageNum=2, pageSize=3, startRow=3, endRow=6, total=9, pages=3, reasonable=false, pageSizeZero=true}[App{id=5, name='insert5'}, App{id=6, name='insert6'}, App{id=7, name='insert7'}]全体の出力結果は次のとおりです:
User{id=2, name='update'} User{id=3, name='insert'} User{id=4, name='insert'} User{id=5, name='insert'} User{id=6, name='insert'} User{id=7, name='insert'} User{id=8, name='insert'} User{id=9, name='insert'} User{id=10, name='insert'} usersByPage = [User{id=5, name='insert'}, User{id=6, name='insert'}, User{id=7, name='insert'}] App{id=2, name='update'} App{id=3, name='insert3'} App{id=4, name='insert4'} App{id=5, name='insert5'} App{id=6, name='insert6'} App{id=7, name='insert7'} App{id=8, name='insert8'} App{id=9, name='insert9'} App{id=10, name='insert10'} pageList = Page{count=true, pageNum=2, pageSize=3, startRow=3, endRow=6, total=9, pages=3, reasonable=false, pageSizeZero=true}[App{id=5, name='insert5'}, App{id=6, name='insert6'}, App{id=7, name='insert7'}] User{id=2, name='update'} User{id=3, name='insert'} User{id=4, name='insert'} User{id=5, name='insert'} User{id=6, name='insert'} User{id=7, name='insert'} User{id=8, name='insert'} User{id=9, name='insert'} User{id=10, name='insert'}
よくある質問
1. 接続タイムアウト
接続タイムアウトの問題が発生した場合、JDBC URLに接続タイムアウトパラメータを設定できます。
jdbc:mysql://host:port/database?connectTimeout=30000&socketTimeout=60000
2. 文字セットの問題
正しい文字エンコーディングを確保するために、JDBC URLに正しい文字セットパラメータを設定します。
jdbc:mysql://host:port/database?characterEncoding=utf8&useUnicode=true
3. SSL接続
OceanBaseデータベースとのSSL接続を有効にするには、JDBC URLに以下のパラメータを追加します。
jdbc:mysql://host:port/database?useSSL=true&requireSSL=true
4. アカウントパスワードの特殊文字
ユーザー名やパスワードに特殊文字(例:#)が含まれている場合は、URLエンコードが必要です。
String encodedPassword = URLEncoder.encode(password, "UTF-8");
注意
MySQL Connector/J 8.xを使用する場合は、アカウントのパスワードにシャープ記号(#)が含まれないようにしてください。含まれていると、接続エラーが発生する可能性があります。
プロジェクトコードについて
java-oceanbase-mybatis をクリックしてプロジェクトコードをダウンロードします。これは java-oceanbase-mybatis という名前の圧縮ファイルです。
解凍すると、java-oceanbase-mybatis という名前のフォルダが作成されます。ディレクトリ構造は以下のとおりです:
│--pom.xml
│
├─.idea
│
├─src
│ ├─main
│ │ ├─java
│ │ │ └─com
│ │ │ └─oceanbase
│ │ │ ├─mapper
│ │ │ │------IAppMapper.java
│ │ │ │------IUserMapper.java
│ │ │ │
│ │ │ └─pojo
│ │ │ │---App.java
│ │ │ └─--User.java
│ │ │
│ │ └─resources
│ │ │--jdbc.properties
│ │ │--mybatis-config.xml
│ │ │
│ │ └─com
│ │ └─oceanbase
│ │ └─mapper
│ │ └─---IUserMapper.xml
│ │
│ └─test
│ └─java
│ └─---TestMybatis.java
│
└─target
ファイルの説明:
pom.xml:Mavenプロジェクトの設定ファイルで、プロジェクトの依存関係、プラグイン、ビルドなどの情報が含まれます。.idea:IDE(統合開発環境)で使用されるディレクトリで、プロジェクト関連の設定情報を格納します。src:プロジェクトのソースコードを格納するディレクトリです。main: 主要なソースコードとリソースファイルを格納するディレクトリ。java: Javaソースコードを格納するディレクトリ。com: Javaパッケージのルートディレクトリ。oceanbase: プロジェクトのルートディレクトリ。mapper: MyBatisのMapperインターフェースとXMLファイルを格納します。IAppMapper.java:アプリケーションデータアクセス層のインターフェースを格納します。IUserMapper.java:ユーザーデータアクセス層のインターフェースを格納します。pojo: JavaBeanまたはエンティティクラスを格納します。App.java:アプリケーションエンティティクラスを格納します。User.java:ユーザーエンティティクラスを格納します。resources: 設定ファイルやSQLファイルなどのリソースファイルを格納するディレクトリ。jdbc.properties: データベース接続情報の設定ファイルを格納します。mybatis-config.xml: MyBatisの設定ファイルを格納します。IUserMapper.xml:ユーザーデータアクセス層のXML設定ファイルを格納します。test: テストコードとリソースファイルを格納するディレクトリ。TestMybatis.java: MyBatisをテストするJavaクラスを格納します。target: コンパイル済みのClassファイルやJarパッケージなどのファイルを格納するディレクトリ。
pom.xmlコードの紹介
説明
例を確認するだけの場合は、デフォルトのコードを使用し、変更は不要です。以下の説明に従って、ご自身の要件に応じて pom.xml ファイルを変更することもできます。
pom.xml 設定ファイルの内容は以下のとおりです:
ファイル宣言ステートメント。
このファイルがXMLファイルであり、使用しているXMLバージョンが
1.0、文字エンコーディング方式がUTF-8であることを宣言します。コード:
<?xml version="1.0" encoding="UTF-8"?>POMの名前空間とPOMモデルバージョンの設定。
xmlnsを使用して、POMの名前空間をhttp://maven.apache.org/POM/4.0.0と指定します。xmlns:xsiを使用して、XML名前空間をhttp://www.w3.org/2001/XMLSchema-instanceと指定します。xsi:schemaLocationを使用して、POMの名前空間をhttp://maven.apache.org/POM/4.0.0と指定し、POMのXSDファイルの場所をhttp://maven.apache.org/xsd/maven-4.0.0.xsdと指定します。<modelVersion>要素を使用して、このPOMファイルで使用するPOMモデルバージョンを4.0.0と指定します。
コード:
<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>
</project>
基本情報の設定。
<groupId>を使用して、プロジェクト識別子をcom.oceanbase.exampleと指定します。<artifactId>を使用して、プロジェクトの依存関係をjava-oceanbase-mybatisと指定します。<version>を使用して、プロジェクトのバージョン番号を1.0-SNAPSHOTと指定します。
コード:
<groupId>com.oceanbase.example</groupId>
<artifactId>java-oceanbase-mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<build>を使用して、プロジェクトのビルドプロセスを定義します。<plugins>を使用して、プロジェクトで設定するプラグインを指定します。<plugin>を使用して、プロジェクトで1つのプラグインを設定します。<groupId>を使用して、プロジェクト識別子をorg.apache.maven.pluginsと指定します。<artifactId>を使用して、プロジェクトの依存関係をmaven-compiler-pluginと指定します。<configuration>を使用して、設定するプラグインのパラメータを指定します。<source>を使用して、コンパイラのソースコードバージョンを8と指定します。<target>を使用して、コンパイラのターゲットコードバージョンを8と指定します。
コード:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>を使用して、プロジェクトが依存するコンポーネントを定義します。依存関係が属する組織を
com.oceanbase、名前をoceanbase-client、バージョン番号を2.4.2と指定します。コード:
<dependencies> <dependency> <groupId>com.oceanbase</groupId> <artifactId>oceanbase-client</artifactId> <version>2.4.2</version> </dependency> </dependencies>依存関係が属するテストフレームワークを
junit、名前をjunit、バージョン番号を4.10と指定します。コード:
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> </dependencies>依存関係が属するフレームワークを
org.mybatis、名前をmybatis、バージョン番号を3.5.9と指定します。コード:
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> </dependencies>依存関係が属するプラグインを
com.github.pagehelper、名前をpagehelper、バージョン番号を5.3.0と指定します。コード:
<dependencies> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.3.0</version> </dependency> </dependencies>
jdbc.propertiesコードの紹介
jdbc.propertiesはプロパティファイルであり、データベース接続に関連する設定情報(データベースのURL、ユーザー名、パスワードなど)を格納するために使用されます。コードの内容は以下のとおりです:
説明
コード内の各フィールドの値は、ステップ1:OceanBaseデータベース接続文字列を取得するから直接取得します。
jdbc.driver:データベースドライバのクラス名で、データベースドライバをロードするために使用されます。jdbc.url:データベースのURLアドレスで、接続するデータベースを指定するために使用されます。jdbc.username:データベースのユーザー名で、データベース接続の認証に使用されます。jdbc.password:データベースのパスワードで、データベース接続の認証に使用されます。
コード:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://host:port/TEST?useServerPrepStmts=true&rewriteBatchedStatements=true
jdbc.username=user_name
jdbc.password=******
mybatis-config.xmlの紹介
mybatis-config.xml ファイルは、MyBatisフレームワークのグローバルプロパティやプラグインなどを設定するために使用されます。
mybatis-config.xml ファイルのコードは、主に以下の部分で構成されています:
ファイル宣言。
このファイルがXMLファイルであることを宣言します。この宣言は、現在のドキュメントがMyBatisの設定ファイルであり、使用しているXMLバージョンが
1.0、文字エンコーディング方式がUTF-8であることを示します。バージョン番号は3.0、言語は英語で、MyBatis公式Webサイトが提供するDTD(Document Type Definition)ファイルを使用して検証されています。宣言には以下の部分が含まれます:
version:XMLファイルのバージョンを指定します。encoding:XMLファイルのエンコーディング方式を指定します。DOCTYPE:ドキュメントタイプ宣言であることを宣言します。configuration:ドキュメントタイプをMyBatis設定ファイルとして指定します。PUBLIC:ドキュメントタイプを公開ドキュメントタイプとして指定します。mybatis.org:MyBatis公式Webサイトを表します。DTD Config 3.0:MyBatis設定ファイルのバージョン番号を表します。EN:ドキュメントタイプの言語が英語であることを表します。
コード:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">読み込むプロパティファイルのパスとファイル名を指定します。
<properties resource="jdbc.properties"></properties>MyBatisのグローバル設定を構成します。
MyBatisのグローバル設定には以下の部分が含まれます:
setting:キャッシュ、ログなどの個々の設定項目を構成するために使用されます。cacheEnabled:キャッシュ機能を有効または無効にするために使用されます。trueに設定します。lazyLoadingEnabled:遅延ロード機能を有効または無効にするために使用されます。trueに設定します。aggressiveLazyLoading:積極的遅延ロード機能を有効または無効にするために使用されます。trueに設定します。multipleResultSetsEnabled:複数結果セットのサポートを有効にするかどうかを構成するために使用されます。trueに設定します。useColumnLabel:結果セット内の列名として列ラベルを使用するかどうかを構成するために使用されます。trueに設定します。useGeneratedKeys:自動生成された主キーを使用するかどうかを構成するために使用されます。trueに設定します。autoMappingBehavior:自動マッピングの処理動作を構成するために使用されます。PARTIALに設定します。defaultExecutorType:デフォルトのエグゼキュータータイプを構成するために使用されます。SIMPLEに設定します。mapUnderscoreToCamelCase:データベース列名のアンダースコアをJavaオブジェクトのプロパティ名のキャメルケースに変換するかどうかを構成するために使用されます。trueに設定します。localCacheScope:ローカルキャッシュのスコープを構成するために使用されます。SESSIONに設定します。jdbcTypeForNull:NULL値を処理する際に使用するJDBCタイプを構成するために使用されます。NULLに設定します。
説明
settings要素内の子要素はオプションであり、実際の状況に応じて追加または削除できます。
コード:
<settings> <!-- Enable or disable caching for global mappers. --> <setting name="cacheEnabled" value="true"/> <!-- Enable or disable lazy loading globally. When disabled, all associated objects are loaded immediately. --> <setting name="lazyLoadingEnabled" value="true"/> <!-- When enabled, objects with delayed loading properties will fully load any properties when called. Otherwise, each attribute will be loaded as needed. --> <setting name="aggressiveLazyLoading" value="true"/> <!-- Allow a single SQL statement to return multiple datasets (depending on driver compatibility) default: true --> <setting name="multipleResultSetsEnabled" value="true"/> <!-- Can column aliases be used (depending on driver compatibility) default: true --> <setting name="useColumnLabel" value="true"/> <!-- Allow JDBC to generate primary keys. Drive support is required. If set to true, this setting will force the use of the generated primary key, and some drives may not be compatible but can still be executed. default:false --> <setting name="useGeneratedKeys" value="true"/> <!-- Specify how MyBatis automatically maps the columns of the data base table NONE: Not Implicit PART: Partial FULL: All --> <setting name="autoMappingBehavior" value="PARTIAL"/> <!-- This is the default execution type (SIMPLE: simple; REUSE: executor may repeatedly use prepared statements; BATCH: executor can repeatedly execute statements and batch updates) --> <setting name="defaultExecutorType" value="SIMPLE"/> <!-- Convert fields using camel naming. --> <setting name="mapUnderscoreToCamelCase" value="true"/> <!-- Set the local cache range session: there will be data sharing statement: statement range (so there will be no data sharing) defalut: session --> <setting name="localCacheScope" value="SESSION"/> <!-- When the JDBC type is set to null, some drivers need to specify a value, default: Other, and there is no need to specify a type when inserting null values --> <setting name="jdbcTypeForNull" value="NULL"/> </settings>MyBatisのプラグインを構成します。
MyBatisのプラグインには以下の部分が含まれます:
plugin:個々のプラグインを構成するために使用されます。property:プラグインのプロパティを指定するために使用されます。interceptor:プラグインの実装クラスを指定するために使用されます。helperDialect:選択したデータベースを指定するために使用されます。offsetAsPageNum:offsetパラメータをpageNumパラメータとして使用するかどうかを示します。rowBoundsWithCount:countクエリを実行するかどうかを示します。pageSizeZero:pageSizeが0のクエリをサポートするかどうかを示します。reasonable:合理化クエリを有効にするかどうかを示します。params:ページネーションパラメータを渡すためのパラメータ名とパラメータ値のマッピング関係を示します。supportMethodsArguments:メソッドパラメータを使用してページネーションパラメータを渡すことをサポートするかどうかを示します。returnPageInfo:戻り値のタイプを示します。
コード:
<plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- this parameter indicates which database to connect to --> <!--MySQLMode dialect<property name="helperDialect" value="mysql"/>--> <!--OracleMode dialect --> <property name="helperDialect" value="mysql"/> <!-- This parameter defaults to false. When set to true, the first parameter offset of RowBounds will be used as the pageNum page number, similar to the pageNum effect in startPage --> <property name="offsetAsPageNum" value="true"/> <!-- This parameter defaults to false, and when set to true, using RowBounds pagination will result in a count query --> <property name="rowBoundsWithCount" value="true"/> <!-- When set to true, if pageSize=0 or RowBounds. limit=0, all results will be queried (equivalent to not executing a pagination query, but the returned results are still of type Page) --> <property name="pageSizeZero" value="true"/> <!-- Version 3.3.0 is available - pagination parameter rationalization is disabled by default as false. When rationalization is enabled, if pageNum<1, the first page will be queried, and if pageNum>pages, the last page will be queried. Rationalization of paging parameters. When rationalization is disabled, if pageNum<1 or pageNum>pages returns empty data --> <property name="reasonable" value="false"/> <!-- Version 3.5.0 is available - In order to support the startPage (Object params) method, a 'params' parameter has been added to configure parameter mapping, which can be used to retrieve values from Map or ServletRequest. PageNum, pageSize, count, pageSizeZero, reasonable, orderBy can be configured. If mapping is not configured, the default value will be used. If you do not understand the meaning, do not copy this configuration casually --> <property name="params" value="pageNum=start;pageSize=limit;"/> <!-- Support passing paging parameters through Mapper interface parameters --> <property name="supportMethodsArguments" value="true"/> <!-- Always always returns PageInfo type, check to check if the return type is PageInfo, and none returns Page --> <property name="returnPageInfo" value="check"/> </plugin>MyBatisの環境を構成します。 MyBatisの環境には以下の部分が含まれます:
environment:個々の環境を構成するために使用されます。transactionManager:トランザクションマネージャーの実装クラスを指定するために使用されます。dataSource:データソースの実装クラスを指定するために使用されます。property:データベースドライバーのクラス名を指定します。
説明
MyBatisの他の設定要素では、
${}プレースホルダーを使用して、環境で構成されたデータソース、トランザクションマネージャー、エグゼキューターなどを参照できます。コード:
<environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments>MyBatisのマッパーを構成します。
MyBatisのマッパーでよく使用される要素は以下のとおりです:
- resource:マッパーのXML設定ファイルのパスとファイル名を指定するために使用されます。
- class:マッパーのJavaクラス名を指定するために使用されます。
説明
XML設定ファイルを使用する場合は、mapper要素でXMLファイルのパスとファイル名を指定する必要があります。Javaインターフェースを使用する場合は、mapper要素でJavaクラスの完全修飾名を指定する必要があります。
コード:
<mappers> <!-- IUserMapper.xml mapping file --> <mapper resource="com/alipay/oceanbase/mapper/IUserMapper.xml"></mapper> <!-- IAppMapper mapping class --> <mapper class="com.oceanbase.mapper.IAppMapper"></mapper> </mappers>
IUserMapper.xmlコードの紹介
IUserMapper.xml ファイルは、ユーザーオブジェクトに関連するSQLステートメントを定義するマッピングファイルです。このファイルでは、ユーザーオブジェクトに関連するSQLステートメントを格納するための IUserMapper という名前空間が定義されています。
説明
例を確認するだけであれば、デフォルトのコードを使用し、変更は不要です。変更が必要な場合は、実際の状況に応じて修正してください。
IUserMapper.xml ファイルのコードは、主に以下の部分で構成されています:
- ファイル宣言ステートメント。 XMLファイルの宣言部分は、XMLファイルのバージョンとエンコーディング方式を指定するために使用されます。DTDファイルの宣言部分は、MyBatisのDTDファイルをインポートするために使用されます。 コード:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
IUserMapper.javaとのマッピング関係の設定。- Javaコード内の
Mapperインターフェースに対応するMapperインターフェースの名前空間を定義します。 insertUserという名前のSQLステートメントを作成し、test_userテーブルにレコードを挿入します。idとnameの2つのフィールドを含み、値はそれぞれ#{id}と#{name}です。parameterType属性は、渡されるパラメータの型をcom.oceanbase.pojo.Userと指定します。deleteUserという名前のSQLステートメントを作成し、test_userテーブルからレコードを削除します。idフィールドの値が#{id}に一致するレコードを削除します。updateUserという名前のSQLステートメントを作成し、test_userテーブル内のレコードを更新します。idフィールドの値が#{id}に一致するレコードのnameフィールドの値を#{name}に更新します。selectUsersという名前のSQLステートメントを作成し、test_userテーブル内のすべてのユーザーレコードを照会します。selectUserByPageという名前のSQLステートメントを作成し、test_userテーブルから指定されたページ数のユーザーオブジェクトを照会します。サブクエリとrownumフィールドを使用してページネーションクエリを実行します。ここで、#{pageNum}と#{pageSize}は、現在のページ番号と1ページあたりのレコード数を表します。
コード:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.oceanbase.mapper.IUserMapper"> <insert id="insertUser" parameterType="com.oceanbase.pojo.User"> INSERT INTO test_user (id,name) VALUES (#{id},#{name}) </insert> <delete id="deleteUser" parameterType="long"> DELETE FROM test_user WHERE id = #{id} </delete> <update id="updateUser" parameterType="com.oceanbase.pojo.User"> UPDATE test_user SET name = #{name} WHERE id = #{id} </update> <select id="selectUsers" resultType="com.oceanbase.pojo.User"> SELECT id,name FROM test_user </select> <!-- There are two ways to paginate queries: 1. Use the pagehelper plugin; 2. Use SQL statements to paginate --> <!-- SQL statement pagination: Oracle mode does not support the limit keyword, and instead uses the unique field 'rownum'--> <select id="selectUserByPage" resultType="com.oceanbase.pojo.User"> select id,name from ( select row_.*, rownum rownum_ from ( select * from test_user ) row_ where rownum <![CDATA[ <= ]]> #{pageNum} * #{pageSize} ) where rownum_ <![CDATA[ >]]> ( #{pageNum}- 1) * #{pageSize} </select> </mapper>- Javaコード内の
IAppMapper.javaのコード紹介
IAppMapper.java ファイルは、SQLマッピング関係を定義するために使用されます。
IAppMapper.java ファイルのコードは、主に以下の部分で構成されています:
Mapperパッケージの定義。このファイルが属するパッケージ名を
com.oceanbase.mapperと宣言します。Mapperパッケージには以下のインターフェースとクラスが含まれます:Appインターフェース:データベーステーブルとのマッピングを表し、データの読み書き操作を実装します。org.apache.ibatis.annotations.*:MyBatisのアノテーションクラスをインポートするために使用されます。java.util.List:java.utilパッケージのListクラスをインポートするために使用されます。 コード:
package com.oceanbase.mapper; import com.oceanbase.pojo.App; import org.apache.ibatis.annotations.*; import java.util.List;IAppMapperインターフェースの定義。IAppMapperインターフェースは、MyBatisのMapperインターフェースを定義するために使用されます。MapperインターフェースはSQLマッピング関係を定義し、データベースに対する追加、削除、変更、検索操作を実装します。具体的には、IAppMapperインターフェースはtest_appテーブルに対する追加、削除、変更、検索のメソッドを定義しており、これには以下が含まれます:@Insertメソッド:データベースにデータを挿入するために使用されます。@Updateメソッド:データベース内のデータを更新するために使用されます。@Deleteメソッド:データベース内のデータを削除するために使用されます。@Selectメソッド:データベース内のデータを検索するために使用されます。@Resultsメソッド:検索結果のマッピング関係を表し、検索結果のフィールドをJavaオブジェクトのプロパティにマッピングするために使用されます。 データベースに対する追加、削除、変更、検索の操作は以下のとおりです:
データの挿入 Appオブジェクトを
test_appテーブル内のレコードにマッピングします。Appオブジェクトのプロパティ値は#{プロパティ名}の形式でプレースホルダーとして表されます。Integer型の戻り値は、SQLステートメントでデータを挿入した後に返される自動生成されたID、すなわちtest_appテーブルのIDフィールドに対応する値を示します。@Insert("insert into test_app(id,name) values(#{id},#{name})") Integer insertApp(App app);データの削除
test_appテーブルから、idが#{id}のデータを削除します。@Delete("delete from test_app where id =#{id}") Integer deleteApp(Long id);データの更新
test_appテーブル内のレコードを変更するには、Update操作を実行する必要があります。@Update("update test_app set name= #{name} where id = #{id}") Integer updateApp(App user);データの検索とマッピング
test_appテーブルのすべてのデータを検索します。同時に、@Resultsアノテーションと@Resultアノテーションを使用して、検索結果をAppオブジェクトのidおよびnameプロパティにマッピングします。最終的にAppオブジェクトのリストを返します。@Update("update test_app set name= #{name} where id = #{id}") Integer updateApp(App user); @Results({ @Result(id = true, column = "id", property = "id"), @Result(column = "name", property = "name") }) List<App> selectApps();
コード:
package com.oceanbase.mapper; import com.oceanbase.pojo.App; import org.apache.ibatis.annotations.*; import java.util.List; public interface IAppMapper { @Insert("insert into test_app(id,name) values(#{id},#{name})") Integer insertApp(App app); @Delete("delete from test_app where id =#{id}") Integer deleteApp(Long id); @Update("update test_app set name= #{name} where id = #{id}") Integer updateApp(App user); @Select("select * from test_app") @Results({ @Result(id = true, column = "id", property = "id"), @Result(column = "name", property = "name") }) List<App> selectApps(); }
IUserMapper.javaのコード紹介
IUserMapper.java ファイルは、データベース操作のメソッドを定義するために使用されます。
IUserMapper.java ファイルのコードは、主に以下の部分で構成されています:
他のクラスとインターフェースのインポート。
このファイルに含まれるインターフェースとクラスを宣言します:
Userクラス:ユーザーオブジェクトを表します。org.apache.ibatis.annotations.Paramクラス:MyBatisフレームワークのパラメータアノテーションです。Listインターフェース:リスト型を表します。 コード:
package com.oceanbase.mapper; import com.oceanbase.pojo.User; import org.apache.ibatis.annotations.Param; import java.util.List;IUserMapperインターフェースの定義。IUserMapperという名前のインターフェースを定義し、ユーザーデータの挿入、削除、更新、クエリのメソッド、およびユーザーデータのページネーションクエリのメソッドを定義しています。また、JavaDocコメントと@Paramアノテーションを使用して、コードの可読性と保守性を向上させています。 コード:public interface IUserMapper { Integer insertUser(User user); Integer deleteUser(Long id); Integer updateUser(User user); List<User> selectUsers(); public List<User> selectUserByPage(@Param("user") User user, @Param("pageNum") Integer pageNum, @Param("pageSize") Integer pageSize); }
App.javaコードの紹介
App.java ファイルは、Appアプリケーションオブジェクトを表すために使用されます。これには id と name の2つの属性が含まれています。クラスには、属性へのアクセスメソッドとコンストラクタメソッド、およびオブジェクトを文字列に変換する toString メソッドも定義されています。
App.java ファイルのコードは、主に以下の部分で構成されています:
pojoパッケージの定義。 このファイルが属するパッケージ名をcom.oceanbase.pojoと宣言します。Appクラスの定義。Appクラスを定義し、2つのプライベート属性idとname、およびパラメータなしのコンストラクタメソッドpublic App(){}を含みます。- パラメータ付きのコンストラクタメソッド
public App(Long id, String name)を定義し、指定されたidとnameを持つアプリケーションオブジェクトを作成するために使用します。 - アプリケーション名の取得と設定を行うための
getIdメソッド、setIdメソッド、getNameメソッド、setNameメソッドを定義します。setNameメソッドは、設定されたアプリケーション名を返します。 toStringメソッドをオーバーライドすることで、アプリケーションオブジェクトを文字列表現に変換し、出力やデバッグを容易にします。
コード:
package com.oceanbase.pojo;
public class App {
private Long id;
private String name;
public App() {
}
public App(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "App{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
User.javaコードの紹介
User.java ファイルは、ユーザーオブジェクトを表すために使用されます。これには id と name の2つの属性が含まれています。クラスには属性へのアクセスメソッドとコンストラクタメソッド、およびオブジェクトを文字列に変換する toString メソッドも定義されています。 このクラスの作成方法は、前述の App.java コードの作成方法と同様です。
コード:
package com.oceanbase.pojo;
public class User {
private Long id;
private String name;
public User() {
}
public User(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
TestMyBatis.javaファイルの紹介
TestMyBatis.javaは、MyBatisを使用してデータ操作を行う方法を示すために使用されます。MyBatisフレームワークの基本機能とSQLステートメントの実行状況、Mapperインターフェースの呼び出し方、SQLステートメントのパラメータと戻り値などをテストします。
他のクラスとインターフェースのインポート。
使用するクラスとインターフェースをインポートするために使用します:
IAppMapperインターフェース:Appオブジェクトに関連するSQLステートメントを定義するために使用されます。IUserMapperインターフェース:Userオブジェクトに関連するSQLステートメントを定義するために使用されます。Appクラス:Appオブジェクト。SQLステートメントの実行状況をテストするために使用されます。Userクラス:Userオブジェクト。SQLステートメントの実行状況をテストするために使用されます。PageHelperプラグイン:ページネーションクエリ機能を実装するために使用されます。PageInfoプラグイン:ページネーションクエリ結果をカプセル化するために使用されます。Resourcesクラス:MyBatis設定ファイルを読み込むために使用されます。SqlSessionクラス:SQLステートメントの実行とトランザクションの管理に使用されます。SqlSessionFactoryクラス:SqlSessionオブジェクトを作成するために使用されます。SqlSessionFactoryBuilderクラス:SqlSessionFactoryオブジェクトを作成するために使用されます。org.junit.Test:JUnitテストフレームワークのアノテーションで、テストメソッドをマークするために使用されます。IOExceptionクラス:入出力操作中のエラーを表すために使用されます。SQLExceptionクラス:SQL操作中のエラーを表すために使用されます。Statementインターフェース:SQLステートメントを実行し、結果を返すために使用されます。java.util.Listインターフェース:要素が重複可能な順序付きコレクションを表すために使用されます。
コード:
import com.oceanbase.mapper.IAppMapper; import com.oceanbase.mapper.IUserMapper; import com.oceanbase.pojo.App; import com.oceanbase.pojo.User; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.IOException; import java.sql.SQLException; import java.sql.Statement; import java.util.List;testUserMapperメソッドの定義。testUserMapperメソッドは、UserオブジェクトのMapperインターフェースで定義されたSQLステートメントの実行状況をテストするために使用されます。SqlSessionFactoryBuilderクラスのbuild()メソッドを使用して、SqlSessionFactoryインスタンスを作成します。SqlSessionインスタンスの作成と破棄を管理するために使用されます。SqlSessionFactoryのopenSession()メソッドを使用して、SqlSessionインスタンスを作成します。クエリ、挿入、更新、削除など、さまざまなSQLステートメントを実行できます。SqlSessionインスタンスのgetConnection()メソッドを使用して、Connectionインスタンスを取得します。さまざまなデータベース操作を実行できます。ConnectionインスタンスのcreateStatement()メソッドを使用して、Statementインスタンスを作成します。SQLステートメントを順次実行します。Statementオブジェクトのexecute()メソッドを使用して、test_userテーブルを削除するSQLステートメントを実行します。Statementオブジェクトのexecute()メソッドを使用して、test_userテーブルを作成します。このテーブルには2つのフィールドが含まれます。1つはidで、number(20)型で主キーとして使用されます。もう1つはnameで、varchar2(100)型です。SqlSessionインスタンスのgetMapper()メソッドを使用して、IUserMapperインターフェースのインスタンスを取得します。さまざまなデータベース操作メソッドを定義します。forループを使用して、test_userテーブルに10件のデータを挿入します。ループごとに新しいUserオブジェクトを作成し、MapperインターフェースのinsertUser()メソッドを使用して挿入操作を実行します。挿入操作の実行結果はinsertResult変数に格納されます。test_userテーブル内のデータを削除、更新、クエリし、最後にforEach()メソッドを使用して、ユーザーリスト内の各ユーザー情報を出力します。insertという名前のユーザーを作成し、selectUserByPage()メソッドを使用してtest_userテーブルから "insert" という名前のすべてのユーザーデータをクエリし、指定されたページのユーザーリストを返します。クエリは2ページ目で、1ページにつき3件のデータを表示します。これらのユーザーデータをコンソールに出力します。同時にStatementとSqlSessionインスタンスを閉じ、トランザクションをコミットしてリソースを解放します。
コード:
public void testUserMapper() throws SQLException, IOException { //mybatis xml usecases SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); SqlSession sqlSession = sqlSessionFactory.openSession(); Statement statement = sqlSession.getConnection().createStatement(); try { statement.execute("drop table test_user"); } catch (SQLException ex) { } finally { statement.execute("create table test_user(id number(20) primary key,name varchar2(100))"); } IUserMapper mapper = sqlSession.getMapper(IUserMapper.class); //insert 10 users for (int i = 1; i <= 10; i++) { User user = new User((long) i, "insert"); Integer insertResult = mapper.insertUser(user); } //delete id==1 Integer deleteResult = mapper.deleteUser(1L); //update id==2L name=update User updateUser = new User(2L, "update"); Integer updateResult = mapper.updateUser(updateUser); //selectUsers query all List<User> userList = mapper.selectUsers(); userList.forEach(System.out::println); //selectUsersByPage:use the rownum keyword in SQL statements to manually perform pagination queries, // example: data on page 2 (3 items per page) User user = new User(); user.setName("insert"); List<User> usersByPage = mapper.selectUserByPage(user, 2, 3); System.out.println("usersByPage = " + usersByPage); statement.close(); sqlSession.commit(); sqlSession.close(); }testSqlSessionメソッドの定義。testSqlSessionメソッドは、SQLSessionオブジェクトの基本機能をテストするために使用されます。SQLステートメントの実行、トランザクションのコミット、SqlSessionオブジェクトの閉じるなどが含まれます。SqlSessionFactoryBuilderクラスのbuild()メソッドを使用して、SqlSessionFactoryインスタンスを作成します。SqlSessionインスタンスの作成と破棄を管理するために使用されます。SqlSessionFactoryのopenSession()メソッドを使用して、SqlSessionインスタンスを作成します。クエリ、挿入、更新、削除など、さまざまなSQLステートメントを実行できます。SqlSessionインスタンスのgetConnection()メソッドを使用して、Connectionインスタンスを取得します。さまざまなデータベース操作を実行できます。ConnectionインスタンスのcreateStatement()メソッドを使用して、Statementインスタンスを作成します。SQLステートメントを順次実行します。Statementオブジェクトのexecute()メソッドを使用して、test_userテーブルを削除するSQLステートメントを実行します。Statementオブジェクトのexecute()メソッドを使用して、test_userテーブルを作成します。このテーブルには2つのフィールドが含まれます。1つはidで、number(20)型で主キーとして使用されます。もう1つはnameで、varchar2(100)型です。forループを使用して、test_userテーブルに10件のデータを挿入します。ループごとに新しいUserオブジェクトを作成し、MapperインターフェースのinsertUser()メソッドを使用して挿入操作を実行します。挿入操作の実行結果はinsertResult変数に格納されます。sqlSessionのdelete()メソッドを使用して、削除操作を実行します。パラメータ1Lを渡して削除条件を設定します。削除操作の結果はdeleteResult変数に格納されます。sqlSessionオブジェクトを使用してデータベースの更新操作を実行します。Userオブジェクトを作成し、updateメソッドを呼び出してSQLステートメントの識別子とパラメータオブジェクトを渡し、更新操作を完了します。具体的なSQLステートメントとパラメータのマッピング関係は、「com.oceanbase.mapper.IUserMapper」インターフェース内のXML設定ファイルで見つけることができます。更新操作の結果はupdateResult変数に格納されます。SqlSessionFactoryのopenSession()メソッドを使用してSqlSessionインスタンスを作成し、そのインスタンスを使用してクエリ操作を実行し、クエリ結果をuserList変数に格納します。最後に、forEachメソッドを使用してuserListを走査し、コンソールに出力します。statement.close()を使用して、データベース接続内のStatementオブジェクトを閉じます。次に、sqlSession.commit()を使用してトランザクションをコミットし、すべての変更をデータベースに永続化します。最後に、sqlSession.close()を使用してSqlSessionオブジェクトを閉じ、関連リソースを解放し、データベース接続を閉じます。
コード:
public void testSqlSession() throws SQLException, IOException { //SqlSession usecases SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); SqlSession sqlSession = sqlSessionFactory.openSession(); Statement statement = sqlSession.getConnection().createStatement(); try { statement.execute("drop table test_user"); } catch (SQLException ex) { } finally { statement.execute("create table test_user(id number(20) primary key,name varchar2(100))"); } //insert for (int i = 1; i <= 10; i++) { User user = new User((long) i, "insert"); //Integer insertResult = mapper.insertUser(user); int insertResult = sqlSession.insert("com.oceanbase.mapper.IUserMapper.insertUser", user); } //delete int deleteResult = sqlSession.delete("com.oceanbase.mapper.IUserMapper.deleteUser", 1L); //update User updateUser = new User(2L, "update"); int updateResult = sqlSession.update("com.oceanbase.mapper.IUserMapper.updateUser", updateUser); //selectUsers List<User> userList = sqlSession.selectList("com.oceanbase.mapper.IUserMapper.selectUsers", null); userList.forEach(System.out::println); //System.out.println("userList = " + userList); statement.close(); sqlSession.commit(); sqlSession.close(); }testAppMapperメソッドの定義。testAppMapperメソッドは、AppMapperの機能をテストするために使用されます。SqlSessionFactoryBuilderクラスのbuild()メソッドを使用して、SqlSessionFactoryインスタンスを作成します。SqlSessionインスタンスの作成と破棄を管理するために使用されます。SqlSessionFactoryのopenSession()メソッドを使用して、SqlSessionインスタンスを作成します。クエリ、挿入、更新、削除など、さまざまなSQLステートメントを実行できます。SqlSessionインスタンスのgetConnection()メソッドを使用して、Connectionインスタンスを取得します。さまざまなデータベース操作を実行できます。ConnectionインスタンスのcreateStatement()メソッドを使用して、Statementインスタンスを作成します。SQLステートメントを順次実行します。Statementオブジェクトのexecute()メソッドを使用して、test_appテーブルを削除するSQLステートメントを実行します。Statementオブジェクトのexecute()メソッドを使用して、test_appテーブルを作成します。このテーブルには2つのフィールドが含まれます。1つはidで、number(20)型で主キーとして使用されます。もう1つはnameで、varchar2(100)型です。SqlSessionインスタンスのgetMapper()メソッドを使用して、IAppMapperインターフェースのインスタンスを取得します。さまざまなデータベース操作メソッドを定義します。forループを使用して、test_appテーブルに10件のデータを挿入します。ループごとに新しいAppオブジェクトを作成し、MapperインターフェースのinsertApp()メソッドを使用して挿入操作を実行します。挿入操作の実行結果はinsertResult変数に格納されます。mapperのdelete()メソッドを使用して、削除操作を実行します。パラメータ1Lを渡して削除条件を設定します。削除操作の結果はdeleteResult変数に格納されます。mapperオブジェクトを使用してデータベースの更新操作を実行します。Appオブジェクトを作成し、updateメソッドを呼び出してSQLステートメントの識別子とパラメータオブジェクトを渡し、更新操作を完了します。idが2L、nameが "update" のAppオブジェクトupdateAppを作成します。mapperのupdateAppメソッドを呼び出し、updateAppオブジェクトを渡して更新操作を実行します。sqlSessionのcommitメソッドを呼び出して、データベーストランザクションをコミットします。mapperのselectAppsメソッドを呼び出して、すべてのAppオブジェクトをクエリします。forEachメソッドを使用してuserListを走査し、コンソールに出力します。PageHelperのstartPageメソッドを呼び出し、ページ番号と1ページあたりのデータ数を渡して、ページネーションパラメータを設定します。すべてのAppオブジェクトをクエリし、すべてのAppオブジェクトを含むListオブジェクトを返します。PageInfoのgetListメソッドを呼び出して、ページネーション後のAppオブジェクトリストを取得し、System.out.printlnメソッドを使用してページネーション後のAppオブジェクトリストを出力します。sqlSession.close()を使用してSqlSessionオブジェクトを閉じ、関連リソースを解放します。
コード:
public void testAppMapper() throws SQLException, IOException { //mybatis annotation usecases SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); SqlSession sqlSession = sqlSessionFactory.openSession(); Statement statement = sqlSession.getConnection().createStatement(); try { statement.execute("drop table test_app"); } catch (SQLException ex) { } finally { statement.execute("create table test_app(id number(20) primary key,name varchar2(100))"); } IAppMapper mapper = sqlSession.getMapper(IAppMapper.class); //insert for (int i = 1; i <= 10; i++) { App app = new App((long) i, "insert" + i); Integer insertResult = mapper.insertApp(app); } //delete Integer deleteResult = mapper.deleteApp(1L); //update App updateApp = new App(2L, "update"); Integer updateResult = mapper.updateApp(updateApp); //commit sqlSession.commit(); //selectApps List<App> appList = mapper.selectApps(); appList.forEach(System.out::println); //selectbyPage //set page parameters PageHelper.startPage(2, 3); //selectApps List<App> appList1 = mapper.selectApps(); //get pageList PageInfo pageInfo = new PageInfo(appList1); List<App> pageList = pageInfo.getList(); System.out.println("pageList = " + pageList); sqlSession.close(); }
全コード表示
<?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.oceanbase.example</groupId>
<artifactId>java-oceanbase-mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.oceanbase</groupId>
<artifactId>oceanbase-client</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!-- pagehelper plug-in -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.0</version>
</dependency>
</dependencies>
</project>
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:oceanbase://host:port/TEST?useServerPrepStmts=true&rewriteBatchedStatements=true
jdbc.username=user_name
jdbc.password=******
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties"></properties>
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="true"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="NULL"/>
</settings>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="oracle"/>
<property name="offsetAsPageNum" value="true"/>
<property name="rowBoundsWithCount" value="true"/>
<property name="pageSizeZero" value="true"/>
<property name="reasonable" value="false"/>
<property name="params" value="pageNum=start;pageSize=limit;"/>
<property name="supportMethodsArguments" value="true"/>
<property name="returnPageInfo" value="check"/>
</plugin>
</plugins>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/alipay/oceanbase/mapper/IUserMapper.xml"></mapper>
<mapper class="com.oceanbase.mapper.IAppMapper"></mapper>
</mappers>
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.oceanbase.mapper.IUserMapper">
<insert id="insertUser" parameterType="com.oceanbase.pojo.User">
INSERT INTO test_user (id,name) VALUES (#{id},#{name})
</insert>
<delete id="deleteUser" parameterType="long">
DELETE FROM test_user WHERE id = #{id}
</delete>
<update id="updateUser" parameterType="com.oceanbase.pojo.User">
UPDATE test_user SET name = #{name} WHERE id = #{id}
</update>
<select id="selectUsers" resultType="com.oceanbase.pojo.User">
SELECT id,name FROM test_user
</select>
<!-- There are two ways to paginate queries: 1. Use the pagehelper plugin; 2. Use SQL statements to paginate -->
<!-- SQL statement pagination: Oracle mode does not support the limit keyword, and instead uses the unique field 'rownum'-->
<select id="selectUserByPage" resultType="com.oceanbase.pojo.User">
select id,name from ( select row_.*, rownum rownum_ from ( select * from test_user ) row_ where rownum
<![CDATA[ <= ]]> #{pageNum} * #{pageSize} ) where rownum_ <![CDATA[ >]]> ( #{pageNum}- 1) * #{pageSize}
</select>
</mapper>
package com.oceanbase.mapper;
import com.oceanbase.pojo.App;
import org.apache.ibatis.annotations.*;
import java.util.List;
//using annotations
public interface IAppMapper {
@Insert("insert into test_app(id,name) values(#{id},#{name})")
Integer insertApp(App app);
@Delete("delete from test_app where id =#{id}")
Integer deleteApp(Long id);
@Update("update test_app set name= #{name} where id = #{id}")
Integer updateApp(App user);
@Select("select * from test_app")
@Results({
@Result(id = true, column = "id", property = "id"),
@Result(column = "name", property = "name")
})
List<App> selectApps();
}
package com.oceanbase.mapper;
import com.oceanbase.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
//using XML
public interface IUserMapper {
Integer insertUser(User user);
Integer deleteUser(Long id);
Integer updateUser(User user);
List<User> selectUsers();
public List<User> selectUserByPage(@Param("user") User user, @Param("pageNum") Integer pageNum,
@Param("pageSize") Integer pageSize);
}
package com.oceanbase.pojo;
public class App {
private Long id;
private String name;
public App() {
}
public App(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "App{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
package com.oceanbase.pojo;
public class User {
private Long id;
private String name;
public User() {
}
public User(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
import com.oceanbase.mapper.IAppMapper;
import com.oceanbase.mapper.IUserMapper;
import com.oceanbase.pojo.App;
import com.oceanbase.pojo.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
public class TestMybatis {
@Test
public void testUserMapper() throws SQLException, IOException {
//mybatis xml usecases
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
Statement statement = sqlSession.getConnection().createStatement();
try {
statement.execute("drop table test_user");
} catch (SQLException ex) {
} finally {
statement.execute("create table test_user(id number(20) primary key,name varchar2(100))");
}
IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
//insert 10 users
for (int i = 1; i <= 10; i++) {
User user = new User((long) i, "insert");
Integer insertResult = mapper.insertUser(user);
}
//delete id==1
Integer deleteResult = mapper.deleteUser(1L);
//update id==2L name=update
User updateUser = new User(2L, "update");
Integer updateResult = mapper.updateUser(updateUser);
//selectUsers query all
List<User> userList = mapper.selectUsers();
userList.forEach(System.out::println);
//selectUsersByPage:use the rownum keyword in SQL statements to manually perform pagination queries,
// example: data on page 2 (3 items per page)
User user = new User();
user.setName("insert");
List<User> usersByPage = mapper.selectUserByPage(user, 2, 3);
System.out.println("usersByPage = " + usersByPage);
statement.close();
sqlSession.commit();
sqlSession.close();
}
@Test
public void testSqlSession() throws SQLException, IOException {
//SqlSession usecases
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
Statement statement = sqlSession.getConnection().createStatement();
try {
statement.execute("drop table test_user");
} catch (SQLException ex) {
} finally {
statement.execute("create table test_user(id number(20) primary key,name varchar2(100))");
}
//insert
for (int i = 1; i <= 10; i++) {
User user = new User((long) i, "insert");
//Integer insertResult = mapper.insertUser(user);
int insertResult = sqlSession.insert("com.oceanbase.mapper.IUserMapper.insertUser", user);
}
//delete
int deleteResult = sqlSession.delete("com.oceanbase.mapper.IUserMapper.deleteUser", 1L);
//update
User updateUser = new User(2L, "update");
int updateResult = sqlSession.update("com.oceanbase.mapper.IUserMapper.updateUser", updateUser);
//selectUsers
List<User> userList = sqlSession.selectList("com.oceanbase.mapper.IUserMapper.selectUsers", null);
userList.forEach(System.out::println);
//System.out.println("userList = " + userList);
statement.close();
sqlSession.commit();
sqlSession.close();
}
@Test
public void testAppMapper() throws SQLException, IOException {
//mybatis annotation usecases
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
Statement statement = sqlSession.getConnection().createStatement();
try {
statement.execute("drop table test_app");
} catch (SQLException ex) {
} finally {
statement.execute("create table test_app(id number(20) primary key,name varchar2(100))");
}
IAppMapper mapper = sqlSession.getMapper(IAppMapper.class);
//insert
for (int i = 1; i <= 10; i++) {
App app = new App((long) i, "insert" + i);
Integer insertResult = mapper.insertApp(app);
}
//delete
Integer deleteResult = mapper.deleteApp(1L);
//update
App updateApp = new App(2L, "update");
Integer updateResult = mapper.updateApp(updateApp);
//commit
sqlSession.commit();
//selectApps
List<App> appList = mapper.selectApps();
appList.forEach(System.out::println);
//selectbyPage
//set page parameters
PageHelper.startPage(2, 3);
//selectApps
List<App> appList1 = mapper.selectApps();
//get pageList
PageInfo pageInfo = new PageInfo(appList1);
List<App> pageList = pageInfo.getList();
System.out.println("pageList = " + pageList);
sqlSession.close();
}
}
関連ドキュメント
OceanBase Connector/Jの詳細については、OceanBase JDBCドライバを参照してください。
クリックしてjava-oceanbase-mybatisサンプルプロジェクトをダウンロード