引言
在上一篇文章中,我們介紹了Mybatis的基礎使用。
如有需要請移步查看:
MyBatis入門:快速掌握用戶查詢實戰https://blog.csdn.net/qq_52331401/article/details/149270402?spm=1001.2014.3001.5502
今天,我將通過一個完整的用戶管理系統示例,深入講解Mybatis的CRUD操作、參數傳遞、模糊查詢以及聚合函數等高級功能。
項目升級概覽
相比基礎版本,本次項目增加了以下功能:
- 完整的CRUD操作(增刪改查)
- 多種查詢方式(ID查詢、模糊查詢)
- 聚合函數使用
- 數據庫連接信息外部化配置
- 更規范的測試類結構
核心代碼解析
實體類(User.java)
實體類保持不變,作為數據載體:
public class User implements Serializable {private Integer id;private String username;private Date birthday;private String sex;private String address;// 省略getter/setter和toString方法
}
Mapper接口(UserMapper.java)
接口中定義了完整的CRUD操作方法:
public interface UserMapper {List<User> findAll(); // 查詢所有用戶User findById(Integer userId); // 根據ID查詢void insert(User user); // 新增用戶void update(User user); // 修改用戶void delete(Integer userId); // 刪除用戶List<User> findByName(String username); // 模糊查詢Integer findByCount(); // 查詢總數
}
Mapper XML配置(UserMapper.xml)
對應接口的SQL實現:
<mapper namespace="cn.tx.mapper.UserMapper"><!-- 查詢所有 --><select id="findAll" resultType="cn.tx.domain.User">select * from user</select><!-- ID查詢 --><select id="findById" resultType="cn.tx.domain.User" parameterType="int">select * from user where id = #{id}</select><!-- 新增用戶(返回自增ID) --><insert id="insert" parameterType="cn.tx.domain.User"><selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">select last_insert_id()</selectKey>insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})</insert><!-- 更新用戶 --><update id="update" parameterType="cn.tx.domain.User">update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}</update><!-- 刪除用戶 --><delete id="delete" parameterType="Integer">delete from user where id=#{id}</delete><!-- 模糊查詢(兩種方式) --><select id="findByName" resultType="cn.tx.domain.User" parameterType="string"><!-- select * from user where username like #{username} -->select * from user where username like '%${value}%'</select><!-- 查詢總數 --><select id="findByCount" resultType="int">select count(*) from user</select>
</mapper>
配置文件優化
數據庫連接信息向上提取到jdbc.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis_db
jdbc.username=root
jdbc.password=123456
SqlMapConfig.xml引用外部配置:
<configuration><properties resource="jdbc.properties"/><!-- 其他配置 --><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>
</configuration>
測試類詳解
測試類采用JUnit4,使用@Before和@After優化:
public class UserTest {private InputStream in;private SqlSession session;private UserMapper mapper;@Beforepublic void init() throws Exception {in = Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);session = factory.openSession();mapper = session.getMapper(UserMapper.class);}@Afterpublic void destory() throws IOException {session.close();in.close();}// 測試方法...
}
查詢測試
@Test
public void testFindAll() {List<User> list = mapper.findAll();list.forEach(System.out::println);
}@Test
public void testFindById() {User user = mapper.findById(1);System.out.println(user);
}
增刪改測試
@Test
public void testInsert() {User user = new User();user.setUsername("測試用戶");user.setBirthday(new Date());user.setSex("男");user.setAddress("北京");mapper.insert(user);session.commit(); // 增刪改需要提交事務System.out.println("新增ID:" + user.getId());
}@Test
public void testUpdate() {User user = mapper.findById(41);user.setUsername("修改后的名字");mapper.update(user);session.commit();
}@Test
public void testDelete() {mapper.delete(48);session.commit();
}
高級查詢測試
// 模糊查詢方式一:參數中帶%
@Test
public void testFindByName() {List<User> list = mapper.findByName("%王%");list.forEach(System.out::println);
}// 模糊查詢方式二:SQL中使用${value}
// 注意:這種方式有SQL注入風險,不推薦@Test
public void testFindByCount() {Integer count = mapper.findByCount();System.out.println("用戶總數:" + count);
}
關鍵技術點解析
參數傳遞
- 簡單類型:#{參數名}
- 對象類型:#{屬性名}
模糊查詢兩種方式
- 安全方式:like #{參數}(需要在參數中包含%)
- 拼接方式:like ‘%${value}%’(有SQL注入風險)
返回自增ID
<selectKey keyProperty="id" order="AFTER" resultType="int">select last_insert_id()
</selectKey>
事務控制
- 增刪改操作需要手動commit()
- 可以再openSession時設置自動提交:openSession(true)
總結
MyBatis的靈活性和強大功能使其成為Java持久層開發的優秀選擇。希望這篇博客能幫助你深入理解MyBatis的核心用法!
完整代碼已提供,建議讀者實際運行測試類體會不同操作的效果。如有任何問題,歡迎留言討論。