LindormTable は、MySQL プロトコルを使用して接続するためのさまざまな方法を提供します。Java オブジェクトリレーショナルマッピング (ORM) フレームワーク MyBatis など、複数の言語とフレームワークをサポートしています。MyBatis フレームワークは、SQL 文をコードから分離します。これにより、データ管理がより柔軟かつ便利になります。MyBatis フレームワークを使用したデータ開発に精通している場合、または SQL 文を統一された方法で管理および最適化したい場合は、MyBatis フレームワークを使用して LindormTable に接続して使用できます。
前提条件
インスタンスで MySQL 互換機能が有効になっています。詳細については、「MySQL 互換機能を有効にする」をご参照ください。
Java 開発キット (JDK) V1.8 以降がインストールされていること。
クライアントの IP アドレスが Lindorm インスタンスのホワイトリストに追加されていること。詳細については、「ホワイトリストを設定する」をご参照ください。
手順
MyBatis と MySQL JDBC ドライバーの依存関係を追加します。たとえば、Maven プロジェクトの場合、
pom.xmlファイルのdependenciesブロックに次の依存関係を追加します。<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.14</version> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.3.0</version> </dependency>resourcesフォルダに、LindormTable の接続情報を格納するためのmybatis-config.xml構成ファイルを作成します。<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://ld-bp1g0p8i3265l****-proxy-lindorm-pub.lindorm.aliyuncs.com:33060/default?sslMode=disabled&allowPublicKeyRetrieval=true&useServerPrepStmts=true&useLocalSessionState=true&rewriteBatchedStatements=true&cachePrepStmts=true&prepStmtCacheSize=100&prepStmtCacheSqlLimit=50000000"/> <property name="username" value="root"/> <property name="password" value="test"/> </dataSource> </environment> </environments> <mappers> <mapper class="org.example.UserMapper"/> </mappers> </configuration>パラメーター
パラメーター
説明
url
MySQL プロトコル用の JDBC 接続アドレスです。フォーマットは
jdbc:mysql://<MySQL 互換エンドポイント>/<データベース名>?<接続構成>です。データベース名を指定しない場合、クライアントはデフォルトのデータベースに接続します。[MySQL 互換エンドポイント] を取得するには、「エンドポイントの表示」をご参照ください。
接続構成によりパフォーマンスが向上します。すべての設定項目を指定してください。詳細については、「接続構成」をご参照ください。
重要アプリケーションが Elastic Compute Service (ECS) インスタンスにデプロイされている場合は、セキュリティを強化し、ネットワーク遅延を低減するために、VPC 経由で Lindorm インスタンスにアクセスします。
アプリケーションがローカルにデプロイされている場合は、インターネット経由で Lindorm インスタンスに接続する前に、コンソールでパブリックエンドポイントを有効にします。これを行うには、コンソールで を選択します。[ワイドテーブルエンジン] タブで、[パブリックエンドポイントを有効にする] をクリックします。
VPC 経由で Lindorm インスタンスにアクセスするには、url パラメーターを MySQL 互換エンドポイントの [VPC] アドレスに設定します。インターネット経由で Lindorm インスタンスにアクセスするには、url パラメーターを MySQL 互換エンドポイントの [パブリック] アドレスに設定します。
username
ユーザーパスワードを忘れた場合は、LindormTable のクラスター管理システムで変更できます。詳細については、「ユーザーパスワードの変更」をご参照ください。
password
オブジェクトクラスを作成します。
package org.example; import java.nio.charset.StandardCharsets; import java.sql.Date; import java.sql.Timestamp; public class User { private int userId; private String userName; private double height; private long score; private Timestamp createTime; private Date birthday; private byte[] digest; public User(int userId, String userName, double height, long score, Timestamp createTime, Date birthday, byte[] digest) { this.userId = userId; this.userName = userName; this.height = height; this.score = score; this.createTime = createTime; this.birthday = birthday; this.digest = digest; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public long getScore() { return score; } public void setScore(long score) { this.score = score; } public Timestamp getCreateTime() { return createTime; } public void setCreateTime(Timestamp createTime) { this.createTime = createTime; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public byte[] getDigest() { return digest; } public void setDigest(byte[] digest) { this.digest = digest; } @Override public String toString() { return "User{" + "userId=" + userId + ", userName='" + userName + '\'' + ", height=" + height + ", score=" + score + ", createTime=" + createTime + ", birthday=" + birthday + ", digest=" + new String(digest, StandardCharsets.UTF_8) + '}'; } }SQL 文とビジネスコード間のマッピングを定義するために MyBatis マッパーを作成します。
import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; package org.example; import java.util.List; public interface UserMapper { @Update("create table if not exists demo_user(`id` INT, `name` VARCHAR, `height` DOUBLE, `score` BIGINT, `createtime` TIMESTAMP, `birthday` DATE, digest VARBINARY,primary key(id))") void createUserTable(); @Update("drop table if exists demo_user") void dropUserTable(); @Insert("upsert into demo_user(`id`,`name`,`height`,`score`,`createtime`,`birthday`,`digest`) values(#{userId},#{userName},#{height},#{score},#{createTime},#{birthday},#{digest})") int upsertUser(User user); @Delete("delete from demo_user where `id` = #{userId}") int deleteUser(@Param("userId") int userId); @Select("select * from demo_user where `id` = #{userId}") User selectOneUser(@Param("userId") int userId); @Select("select * from demo_user") List<User> selectAllUser(); }ビジネスコードを記述します。
package org.example; 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 java.io.InputStream; import java.nio.charset.StandardCharsets; import java.sql.Date; import java.sql.Timestamp; public class MybatisDemo { public static void main(String[] args) throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build( inputStream); try (SqlSession session = sqlSessionFactory.openSession()) { UserMapper mapper = session.getMapper(UserMapper.class); // ユーザーテーブルを作成 mapper.createUserTable(); // すべてのユーザーを選択 System.out.println(mapper.selectAllUser()); User user1 = new User(1, "zhangsan", 1.8, 100, new Timestamp(System.currentTimeMillis()), Date.valueOf("1995-03-02"), "hello".getBytes(StandardCharsets.UTF_8)); User user2 = new User(2, "lisi", 1.7, 90, new Timestamp(System.currentTimeMillis()), Date.valueOf("1996-08-02"), "world".getBytes(StandardCharsets.UTF_8)); // user1 と user2 を挿入 mapper.upsertUser(user1); mapper.upsertUser(user2); // すべてのユーザーを選択 System.out.println(mapper.selectAllUser()); // user1 を選択 System.out.println(mapper.selectOneUser(1)); // user1 を削除 mapper.deleteUser(1); System.out.println(mapper.selectAllUser()); // user2 のスコアを 99 に更新 user2.setScore(99); mapper.upsertUser(user2); System.out.println(mapper.selectAllUser()); // ユーザーテーブルを削除 mapper.dropUserTable(); } } }
完全な例
完全なサンプルコードについては、「mybatis-demo.zip」をご参照ください。
コードが正常に実行されると、次の結果が返されます。
[User{userId=1, userName='zhangsan', height=1.8, score=100, createTime=2023-12-02 09:39:17.63, birthday=1995-03-02, digest=hello}, User{userId=2, userName='lisi', height=1.7, score=90, createTime=2023-12-02 09:39:17.63, birthday=1996-08-02, digest=world}]
User{userId=1, userName='zhangsan', height=1.8, score=100, createTime=2023-12-02 09:39:17.63, birthday=1995-03-02, digest=hello}
[User{userId=2, userName='lisi', height=1.7, score=90, createTime=2023-12-02 09:39:17.63, birthday=1996-08-02, digest=world}]
[User{userId=2, userName='lisi', height=1.7, score=99, createTime=2023-12-02 09:39:17.63, birthday=1996-08-02, digest=world}]