基于Java ORM框架MyBatis的應(yīng)用開發(fā)
Lindorm寬表引擎提供了一系列基于MySQL協(xié)議的連接方式,涉及多種語言和多種框架,其中包括Java對象關(guān)系映射(ORM)框架MyBatis。MyBatis框架實現(xiàn)了SQL與代碼的解耦,使數(shù)據(jù)管理變得更加靈活和方便。如果您習慣使用MyBatis框架進行數(shù)據(jù)開發(fā),或想要對SQL語句進行統(tǒng)一管理和優(yōu)化,推薦您通過Java ORM框架MyBatis連接和使用Lindorm寬表引擎。
前提條件
已開通MySQL協(xié)議兼容功能。如何開通,請參見開通MySQL協(xié)議兼容功能。
已安裝Java環(huán)境,要求安裝JDK 1.8及以上版本。
已將客戶端IP添加至白名單,具體操作請參見設(shè)置白名單。
操作步驟
添加MyBatis和MySQL JDBC Driver依賴。以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.0.33</version> </dependency>
在
resources
目錄下,創(chuàng)建mybatis-config.xml
基礎(chǔ)配置文件,用于保存Lindorm寬表引擎相關(guān)連接信息。<?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-uf6k8yqb741t3****-proxy-sql-lindorm-public.lindorm.rds.aliyuncs.com:33060/default"/> <property name="username" value="root"/> <property name="password" value="test"/> </dataSource> </environment> </environments> <mappers> <mapper class="org.example.UserMapper"/> </mappers> </configuration>
參數(shù)說明
參數(shù)
說明
url
MySQL協(xié)議的Java JDBC連接地址及需要連接的數(shù)據(jù)庫。格式為
jdbc:mysql://<MySQL兼容地址>/<數(shù)據(jù)庫名>
。默認連接default數(shù)據(jù)庫。如何獲取MySQL兼容地址,請參見查看連接地址。
重要如果應(yīng)用部署在ECS實例,建議您通過專有網(wǎng)絡(luò)訪問Lindorm實例,可獲得更高的安全性和更低的網(wǎng)絡(luò)延遲。
如果應(yīng)用部署在本地,在通過公網(wǎng)連接Lindorm實例前,需在控制臺開通公網(wǎng)地址。開通方式:在控制臺選擇
,在寬表引擎頁簽單擊開通公網(wǎng)地址。通過專有網(wǎng)絡(luò)訪問Lindorm實例,url中請?zhí)顚慚ySQL兼容地址對應(yīng)的專有網(wǎng)絡(luò)地址。通過公網(wǎng)訪問Lindorm實例,url中請?zhí)顚慚ySQL兼容地址對應(yīng)的公網(wǎng)地址。
username
如果您忘記用戶密碼,可以通過Lindorm寬表引擎的集群管理系統(tǒng)修改密碼。具體操作,請參見修改用戶密碼。
password
創(chuàng)建對象類。
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) + '}'; } }
創(chuàng)建MyBatis框架的Mapper,用于定義SQL語句與業(yè)務(wù)代碼的映射關(guān)系。
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(); }
編寫業(yè)務(wù)代碼。
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); //create user table mapper.createUserTable(); //select all users 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)); //insert user1 and user2 mapper.upsertUser(user1); mapper.upsertUser(user2); //select all users System.out.println(mapper.selectAllUser()); //select user1 System.out.println(mapper.selectOneUser(1)); //delete user1 mapper.deleteUser(1); System.out.println(mapper.selectAllUser()); //update user2's score to 99 user2.setScore(99); mapper.upsertUser(user2); System.out.println(mapper.selectAllUser()); //drop user table mapper.dropUserTable(); } } }
完整示例
完整示例代碼,請參見mybatis-demo.tar。
執(zhí)行成功后,將返回以下結(jié)果:
[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}]