LindormTable menyediakan berbagai cara untuk terhubung melalui protokol MySQL dan mendukung berbagai bahasa serta framework, termasuk framework Object-Relational Mapping (ORM) Java MyBatis. MyBatis memisahkan pernyataan SQL dari kode aplikasi, sehingga mempermudah manajemen data secara fleksibel dan nyaman. Jika Anda telah terbiasa menggunakan MyBatis dalam pengembangan aplikasi atau ingin mengelola serta mengoptimalkan pernyataan SQL secara terpadu, Anda dapat memanfaatkan MyBatis untuk terhubung ke dan menggunakan LindormTable.
Prasyarat
Fitur kompatibilitas MySQL diaktifkan pada instans tersebut. Untuk informasi selengkapnya, lihat Aktifkan fitur kompatibilitas MySQL.
Java Development Kit (JDK) versi 1.8 atau lebih baru telah diinstal.
Alamat IP klien Anda telah ditambahkan ke daftar putih instans Lindorm Anda. Untuk informasi selengkapnya, lihat Konfigurasi daftar putih.
Prosedur
Tambahkan dependensi MyBatis dan MySQL JDBC Driver. Sebagai contoh, untuk proyek Maven, tambahkan dependensi berikut ke blok
dependenciesdalam filepom.xml:<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>Di folder
resources, buat file konfigurasimybatis-config.xmluntuk menyimpan informasi koneksi ke LindormTable.<?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>Parameter
Parameter
Deskripsi
url
Alamat koneksi JDBC untuk protokol MySQL. Formatnya adalah
jdbc:mysql://<Titik akhir kompatibel MySQL>/<Nama database>?<Konfigurasi koneksi>.Jika Anda tidak menentukan nama database, klien akan terhubung ke database default. Untuk mendapatkan MySQL-compatible Endpoint, lihat Lihat titik akhir.
Konfigurasi koneksi dapat meningkatkan performa. Tentukan semua item konfigurasi. Untuk informasi selengkapnya, lihat Konfigurasi koneksi.
PentingJika aplikasi Anda dideploy pada instans Elastic Compute Service (ECS), akses instans Lindorm melalui virtual private cloud (VPC) untuk keamanan yang lebih tinggi dan latensi jaringan yang lebih rendah.
Jika aplikasi Anda dideploy secara lokal, aktifkan Titik Akhir Publik di Konsol sebelum menghubungkan ke instans Lindorm melalui Internet. Untuk melakukannya, di Konsol, pilih . Di tab Wide Table Engine, klik Enable Public Endpoint.
Untuk mengakses instans Lindorm melalui VPC, atur parameter url ke alamat VPC dari titik akhir kompatibel MySQL. Untuk mengakses instans Lindorm melalui Internet, atur parameter url ke alamat Public dari titik akhir kompatibel MySQL.
username
Jika Anda lupa kata sandi pengguna, Anda dapat mengubahnya di sistem manajemen kluster LindormTable. Untuk informasi selengkapnya, lihat Ubah kata sandi pengguna.
password
Buat kelas objek.
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) + '}'; } }Buat mapper MyBatis untuk mendefinisikan pemetaan antara pernyataan SQL dan kode bisnis.
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(); }Tulis kode bisnis.
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); //buat tabel pengguna mapper.createUserTable(); //pilih semua pengguna 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)); //masukkan user1 dan user2 mapper.upsertUser(user1); mapper.upsertUser(user2); //pilih semua pengguna System.out.println(mapper.selectAllUser()); //pilih user1 System.out.println(mapper.selectOneUser(1)); //hapus user1 mapper.deleteUser(1); System.out.println(mapper.selectAllUser()); //perbarui skor user2 menjadi 99 user2.setScore(99); mapper.upsertUser(user2); System.out.println(mapper.selectAllUser()); //hapus tabel pengguna mapper.dropUserTable(); } } }
Contoh lengkap
Untuk kode contoh lengkap, lihat mybatis-demo.zip.
Setelah kode berhasil dijalankan, hasil berikut dikembalikan:
[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}]