MyBatis項目的創(chuàng)建和增刪查改操作詳解
1. 項目的創(chuàng)建
第一步還是和之前的 Spring 項目一樣
然后還需要添加以下依賴,Lombok 和 web 依賴也可以加上
之后需要進行數(shù)據(jù)庫的配置,這里通過 yml 來演示:
spring: application: name: mybatis-demo datasource: url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=false username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver
2. 中文亂碼問題解決
yml 配置文件中,可能中文會出現(xiàn)亂碼,可以設(shè)置 idea 中的編碼方式來避免亂碼
為了避免之后創(chuàng)建的項目也出現(xiàn)亂碼,還需要更改一下新項目的設(shè)置
3. MyBatis 的簡單操作
3.1. 查詢
可以把數(shù)據(jù)庫中的表的字段抽象為一個對象進行描述
@Data public class UserInfo { private Integer id; private String username; private String password; private Integer age; private Integer gender; private String phone; private Integer deleteFlag; private Date createTime; private Date updateTime; }
然后定義接口進行查詢
@Mapper public interface UserInfoMapper { //查詢所有的用戶信息 @Select("select * from user_info") List<UserInfo> selectAll(); }
在 Spring Boot 工程中,已經(jīng)自動創(chuàng)建好了測試類,可以在這個類中進行測試
@SpringBootTest class MybatisDemoApplicationTests { @Autowired private UserInfoMapper userInfoMapper; @Test void contextLoads() { System.out.println(userInfoMapper.selectAll()); } }
3.1.1. 駝峰轉(zhuǎn)化
表中的數(shù)據(jù)都被轉(zhuǎn)化為一個對象信息打印出來了,但是發(fā)現(xiàn)有幾個字段是沒有賦值的,只有和 java 對象屬性和數(shù)據(jù)庫字段一樣時才會進行賦值
但是由于數(shù)據(jù)庫的命名規(guī)范和 java 的命名規(guī)范是不一樣的,java 中駝峰命名,如果想要保持一致的話,可以進行別名的方式
@Select("select id, username, password, age, gender, phone, " + "delete_flag as deleteFlag, create_time as createTime, update_time as updateTime from user_info") List<UserInfo> selectAll();
除了這種方式之外還可以通過注解來存儲映射:
一個@Results
注解中以數(shù)組的形式存儲@Result
注解
@Results({ @Result(column = "delete_flag", property = "deleteFlag"), @Result(column = "create_time", property = "createTime"), @Result(column = "update_time", property = "updateTime"), }) @Select("select id, username, password, age, gender, phone, delete_flag, create_time, update_time from user_info") List<UserInfo> selectAll();
和上面的方式不同的是,這里配置一次映射整個類都可以用
@Results(id = "BaseMap", value = { @Result(column = "delete_flag", property = "deleteFlag"), @Result(column = "create_time", property = "createTime"), @Result(column = "update_time", property = "updateTime"), })
這里指定好 id 之后,其他方法也就可以通過使用@ResultMap
注解使用到了:
@ResultMap("BaseMap") @Select("select id, username, password, age, gender, phone, delete_flag, create_time, update_time from user_info where id= #{aa}") UserInfo selectId(Integer id);
上面這些方法寫起來還是有些麻煩的,可以直接通過配置文件的方式,配置駝峰轉(zhuǎn)化
mybatis: configuration: map-underscore-to-camel-case: true #配置駝峰自動轉(zhuǎn)換
這樣直接搞定,無論上面的別名還是注解,都不用寫
3.2. 單元測試
除了上面的測試方法之外,還可以使用 idea 自動生成測試類
首先在需要測試的 Mapper 接口中右鍵之后點 Generate,然后再點 Test
然后就可以選擇要測試的方法,就會自動生成單元測試類
生成的測試類需要加上 @SpringBootTest
注解
3.3. 打印日志
在 MyBatis 中可以借助日志來查看到 SQL 語句的執(zhí)行,執(zhí)行傳遞的參數(shù)和執(zhí)行結(jié)果,可以現(xiàn)在配置文件中進行配置:
mybatis: configuration: # 配置打印 MyBatis日志 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
配置好之后多了下面的一些信息
通過這些信息也可以幫助我們?nèi)グl(fā)現(xiàn)問題
3.4. 參數(shù)傳遞
如果說想要查詢 id = 4 的用戶,那么就可以這樣寫
@Select("select * from user_info where id = 4") UserInfo selectId();
這時返回值就可以用一個對象來接收了,上面的方式中參數(shù)就寫的固定了,如果說把傳入的 id 作為參數(shù)傳遞,就靈活很多
MyBatis 中是通過使用#{}
的方式進行參數(shù)傳遞的:
@Select("select * from user_info where id = #{id}") UserInfo selectId(Integer id);
并且在一個參數(shù)的情況下,這兩個參數(shù)是可以不對應(yīng)的,但是如果是多個參數(shù),就需要相互對應(yīng)了
來看多個參數(shù)的情況:
@Select("select * from user_info where age = #{age} and gender = #{gender}") List<UserInfo> selectUserByAgeAndGender(Integer age,Integer gender);
由于是按照參數(shù)名稱匹配的,所以參數(shù)順序換一換也是沒問題的,但是名稱一定要匹配,如果名稱匹配不上是會報錯的
還有另一種寫法,還可以通過 param1, param2 這樣的方式來匹配,不過還是推薦使用第一種寫法
還可以使用@Param
對參數(shù)進行重命名:
@Select("select * from user_info where age = #{age} and gender = #{gender}") List<UserInfo> selectUserByAgeAndGender(@Param("gender") Integer gender, @Param("age") Integer age);
但是如果重命名的參數(shù)和 SQL 語句中的參數(shù)不匹配也是會報錯的
還是推薦重命名之后的參數(shù)和 SQL 的參數(shù)都保持一致,也就是參數(shù)和注解中的名稱也要保持一致:
@Select("select * from user_info where age = #{age} and gender = #{gender}") List<UserInfo> selectUserByAgeAndGender(@Param("gender") Integer gender, @Param("age") Integer age);
3.5. 增加
插入的話,由于表中有多個字段,可以直接傳入一個對象,對象的屬性就代表這些字段
@Insert("insert into user_info(username,password,age,gender) " + "values (#{username},#{password},#{age},#{gender})") Integer insertUser(UserInfo userInfo);
然后測試一下
@Test void insertUser() { UserInfo userInfo = new UserInfo(); userInfo.setUsername("xxx"); userInfo.setPassword("111"); userInfo.setAge(19); userInfo.setGender(1); Integer integer = userInfoMapper.insertUser(userInfo); }
在 mysql 的日志中也是成功的更新了
如果說要想上面那樣通過參數(shù)重命名的方式的話,來看一下結(jié)果:
這里發(fā)現(xiàn)是報錯了,如果使用重命名,SQL 語句中的參數(shù)是需要通過對象來獲取屬性的
insert 語句默認返回的是影響的行數(shù),如果想要獲取自增 id 的話需要在方法上再加上一個@Options
注解
@Test void insertUser() { UserInfo userInfo = new UserInfo(); userInfo.setUsername("xxx"); userInfo.setPassword("111"); userInfo.setAge(19); userInfo.setGender(1); Integer integer = userInfoMapper.insertUser(userInfo); System.out.println("影響行數(shù):" + integer + ",自增id:" + userInfo.getId()); }
方法的返回值還是影響行數(shù),也是成功拿到了自增 id
3.6. 刪除
刪除的返回值也是影響的行數(shù)
@Delete("delete from user_info where id = #{id}") Integer deleteId(Integer id);
3.7. 修改
修改數(shù)據(jù)也是影響的行數(shù)
@Update("update user_info set password = #{password} where id = #{id}") Integer update(Integer id,String password);
以上就是MyBatis項目的創(chuàng)建和增刪查改操作詳解的詳細內(nèi)容,更多關(guān)于MyBatis項目創(chuàng)建和增刪改查的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
MyBatis Plus實現(xiàn)一對多的查詢場景的三種方法
MyBatis Plus提供了多種簡便的方式來進行一對多子查詢,本文主要介紹了MyBatis Plus實現(xiàn)一對多的查詢場景的三種方法,具有一定的參考價值,感興趣的可以了解一下2024-07-07IDEA中Directory創(chuàng)建多級目錄的實現(xiàn)
本文主要介紹了IDEA中Directory創(chuàng)建多級目錄的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06Spring和IDEA不推薦使用@Autowired?注解原因解析
這篇文章主要為大家介紹了Spring和IDEA不推薦使用@Autowired?注解原因解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07IDEA搭建SpringBoot多模塊聚合工程過程詳解(多模塊聚合工程)
這篇文章主要是介紹一下,如何在IDEA開發(fā)工具下,搭建一個基于SpringBoot的多模塊聚合工程項目,本篇文章,將項目模塊細分為幾個子工程模塊,在文中給大家詳細介紹過,對IDEA搭建SpringBoot多模塊聚合工程感興趣的朋友一起看看吧2022-04-04Spring Transaction事務(wù)實現(xiàn)流程源碼解析
此文就Spring 事務(wù)實現(xiàn)流程進行源碼解析,我們可以借此對Spring框架更多一層理解,下面以xml形式創(chuàng)建一個事務(wù)進行分析2022-09-09JVM調(diào)優(yōu)OutOfMemoryError異常分析
這篇文章主要為大家介紹了JVM調(diào)優(yōu)OutOfMemoryError異常分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11深入理解happens-before和as-if-serial語義
本文大部分整理自《Java并發(fā)編程的藝術(shù)》,溫故而知新,加深對基礎(chǔ)的理解程度。下面可以和小編來一起學(xué)習(xí)下2019-05-05