更新時間:2021-12-20 09:31:25 來源:動力節點 瀏覽881次
本章節將通過一個 MyBatis 實例,讓你快速 MyBatis 入門。學習 MyBatis 查詢、新增、修改和刪除操作的基礎用法,實現該實例的步驟如下:
配置數據庫信息,如:數據庫URL、驅動、用戶名、密碼等信息
編寫 mybatis-cfg.xml 配置文件,配置 mybatis 數據源、mapper等
定義數據庫 user 表的實體映射類 UserBean
定義 Mapper 接口文件,UserMapper.java 文件
定義 Mapper XML 文件,UserMapper.xml 文件
最后編寫測試用例 Main.java 類
實例代碼如下:
(1)數據庫 database.properties 配置文件
# 數據庫信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_test?useUnicode=true&characterEncoding=UTF8
jdbc.username=root
jdbc.password=aaaaaa
(2)mybaits-cfg.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>
<properties resource="database.properties"/>
<environments default="MySqlDatabase" >
<environment id="MySqlDatabase" >
<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>
<package name="mybatis.simple.mapper"/>
</mappers>
</configuration>
(3)定義 user 表的實體類 UserBean.java,代碼如下:
package mybatis.simple.mode;
import java.util.Arrays;
import java.util.Date;
public class UserBean {
private Integer userId;
private String name;
private String sex;
private Integer age;
private Double salary;
private Date borthday;
private byte[] face;
public UserBean() {}
public UserBean(int userId, String name, String sex, int age) {
this.userId = userId;
this.name = name;
this.sex = sex;
this.age = age;
}
// 忽略 getter 和 setter 方法
@Override
public String toString() {
return "UserBean{" +
"userId=" + userId +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", salary=" + salary +
", borthday=" + borthday +
", face=" + Arrays.toString(face) +
'}';
}
}
(4)定義 Mapper 接口類 UserMapper.java,代碼如下:
package mybatis.simple.mapper;
import java.util.List;
import mybatis.simple.mode.UserBean;
public interface UserMapper {
/** 查詢所有用戶信息 */
public List<UserBean> findAll();
/** 根據ID查詢用戶信息 */
public UserBean findById(int userId);
/** 保存用戶信息 */
public int saveUser(UserBean user);
/** 更新用戶信息 */
public int updateUser(UserBean user);
/** 根據用戶ID刪除用戶信息 */
public int deleteUser(int userId);
}
(5)編寫 Mapper XML 文件 UserMapper.xml,代碼如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mybatis.simple.mapper.UserMapper">
<!-- 映射結果 -->
<resultMap id="RESULT_MAP" type="mybatis.simple.mode.UserBean">
<id column="user_id" jdbcType="INTEGER" property="userId" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="VARCHAR" property="sex" />
<result column="age" jdbcType="INTEGER" property="age" />
<result column="salary" jdbcType="DOUBLE" property="salary" />
<result column="borthday" jdbcType="DATE" property="borthday" />
<result column="face" jdbcType="LONGVARBINARY" property="face" />
</resultMap>
<!-- 查詢所有用戶信息 -->
<select id="findAll" resultMap="RESULT_MAP">
select `user_id`, `name`, `sex`, `age`, `salary`, `borthday`, `face`
from `user`
</select>
<!-- 根據用戶ID查找用戶信息 -->
<select id="findById" parameterType="int" resultMap="RESULT_MAP">
select `user_id`, `name`, `sex`, `age`, `salary`, `borthday`, `face`
from `user`
where `user_id`=#{userId,jdbcType=INTEGER}
</select>
<!-- 保存用戶信息 -->
<insert id="saveUser">
INSERT INTO `user`(
`user_id`, `name`, `sex`, `age`, `salary`, `borthday`, `face`
) VALUES (
#{userId,jdbcType=VARCHAR},
#{name,jdbcType=VARCHAR},
#{sex,jdbcType=INTEGER},
#{age,jdbcType=VARCHAR},
#{salary,jdbcType=INTEGER},
#{borthday,jdbcType=VARCHAR},
#{face,jdbcType=INTEGER}
)
</insert>
<!-- 更新用戶信息 -->
<update id="updateUser" parameterType="hashmap">
UPDATE `user` SET
`name`=#{name, jdbcType=VARCHAR},
`sex`=#{sex, jdbcType=VARCHAR},
`age`=#{age, jdbcType=INTEGER},
`salary`=#{salary, jdbcType=DOUBLE},
`borthday`=#{borthday, jdbcType=DATE},
`face`=#{face, jdbcType=BLOB}
WHERE `user_id`=#{userId,jdbcType=INTEGER}
</update>
<!-- 刪除用戶信息 -->
<delete id="deleteUser" parameterType="int">
DELETE FROM `user` WHERE `user_id`=#{userId, jdbcType=INTEGER}
</delete>
</mapper>
(6)編寫測試類 Main.java,代碼如下:
package mybatis.simple;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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 mybatis.simple.mapper.UserMapper;
import mybatis.simple.mode.UserBean;
public class Main {
public static void main(String[] args) throws Exception {
new Main();
}
public Main() throws IOException {
// 獲取 Mapper 對象
String cfgName = "mybatis-cfg.xml";
InputStream input = Resources.getResourceAsStream(cfgName);
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlFactory = factoryBuilder.build(input);
SqlSession sqlSession = sqlFactory.openSession(true);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 插入兩個用戶
System.out.println("插入用戶信息……");
UserBean user1 = new UserBean(10, "ZhangSan", "male", 28);
UserBean user2 = new UserBean(30, "ZhaoLiu", "female", 32);
userMapper.saveUser(user1);
userMapper.saveUser(user2);
// 查詢所有用戶信息
System.out.println("查詢所有用戶信息:");
List<UserBean> userList = userMapper.findAll();
for(UserBean user : userList) {
System.out.println("\t用戶信息=" + user);
}
// 查詢 ID 等于 10 的用戶
System.out.println("根據ID查詢用戶信息:");
UserBean userBean = userMapper.findById(10);
System.out.println("\t用戶信息=" + userBean);
// 更新用戶
System.out.println("更新用戶信息:");
UserBean updateUser = new UserBean(10, "ZhaoLiu-Update", "male", 22);
userMapper.updateUser(updateUser);
System.out.println("\t用戶信息=" + userMapper.findById(10));
// 刪除用戶
System.out.println("刪除用戶信息……");
userMapper.deleteUser(10);
userMapper.deleteUser(30);
}
}
實例運行結果如下:
插入用戶信息……
查詢所有用戶信息:
用戶信息=UserBean{userId=10, name='ZhangSan', sex='male', age=28, salary=null, borthday=null, face=null}
用戶信息=UserBean{userId=30, name='ZhaoLiu', sex='female', age=32, salary=null, borthday=null, face=null}
根據ID查詢用戶信息:
用戶信息=UserBean{userId=10, name='ZhangSan', sex='male', age=28, salary=null, borthday=null, face=null}
更新用戶信息:
用戶信息=UserBean{userId=10, name='ZhaoLiu-Update', sex='male', age=22, salary=null, borthday=null, face=null}
刪除用戶信息……
到了這里,你已經對使用 MyBatis 進行開發有一個完整的認識了,在后續的章節將按不同的部分對 MyBatis 進行全面介紹。如果您想了解更多相關知識,不妨來關注一下動力節點的Java視頻教程,里面的內容更加詳細,從入門到精通,適合小白學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習