更新時(shí)間:2021-12-20 09:31:25 來(lái)源:動(dòng)力節(jié)點(diǎn) 瀏覽874次
本章節(jié)將通過(guò)一個(gè) MyBatis 實(shí)例,讓你快速 MyBatis 入門(mén)。學(xué)習(xí) MyBatis 查詢、新增、修改和刪除操作的基礎(chǔ)用法,實(shí)現(xiàn)該實(shí)例的步驟如下:
配置數(shù)據(jù)庫(kù)信息,如:數(shù)據(jù)庫(kù)URL、驅(qū)動(dòng)、用戶名、密碼等信息
編寫(xiě) mybatis-cfg.xml 配置文件,配置 mybatis 數(shù)據(jù)源、mapper等
定義數(shù)據(jù)庫(kù) user 表的實(shí)體映射類(lèi) UserBean
定義 Mapper 接口文件,UserMapper.java 文件
定義 Mapper XML 文件,UserMapper.xml 文件
最后編寫(xiě)測(cè)試用例 Main.java 類(lèi)
實(shí)例代碼如下:
(1)數(shù)據(jù)庫(kù) database.properties 配置文件
# 數(shù)據(jù)庫(kù)信息
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 表的實(shí)體類(lèi) 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 接口類(lèi) UserMapper.java,代碼如下:
package mybatis.simple.mapper;
import java.util.List;
import mybatis.simple.mode.UserBean;
public interface UserMapper {
/** 查詢所有用戶信息 */
public List<UserBean> findAll();
/** 根據(jù)ID查詢用戶信息 */
public UserBean findById(int userId);
/** 保存用戶信息 */
public int saveUser(UserBean user);
/** 更新用戶信息 */
public int updateUser(UserBean user);
/** 根據(jù)用戶ID刪除用戶信息 */
public int deleteUser(int userId);
}
(5)編寫(xiě) 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">
<!-- 映射結(jié)果 -->
<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>
<!-- 根據(jù)用戶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)編寫(xiě)測(cè)試類(lèi) 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 對(duì)象
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);
// 插入兩個(gè)用戶
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("根據(jù)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);
}
}
實(shí)例運(yùn)行結(jié)果如下:
插入用戶信息……
查詢所有用戶信息:
用戶信息=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}
根據(jù)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}
刪除用戶信息……
到了這里,你已經(jīng)對(duì)使用 MyBatis 進(jìn)行開(kāi)發(fā)有一個(gè)完整的認(rèn)識(shí)了,在后續(xù)的章節(jié)將按不同的部分對(duì) MyBatis 進(jìn)行全面介紹。如果您想了解更多相關(guān)知識(shí),不妨來(lái)關(guān)注一下動(dòng)力節(jié)點(diǎn)的Java視頻教程,里面的內(nèi)容更加詳細(xì),從入門(mén)到精通,適合小白學(xué)習(xí),希望對(duì)大家能夠有所幫助。
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問(wèn)老師會(huì)電話與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743