<noframes id="bhrfl"><address id="bhrfl"></address>

    <address id="bhrfl"></address>

    <noframes id="bhrfl"><address id="bhrfl"><th id="bhrfl"></th></address>

    <form id="bhrfl"><th id="bhrfl"><progress id="bhrfl"></progress></th></form>

    <em id="bhrfl"><span id="bhrfl"></span></em>

    全部
    常見問題
    產品動態
    精選推薦

    使用MyBatis訪問MySQL

    管理 管理 編輯 刪除

    之前我們了解了兩種在Spring Boot中訪問關系型數據庫的方式:

    使用JdbcTemplate訪問MySQL數據庫

    使用Spring Data JPA訪問MySQL

    雖然Spring Data JPA在國外廣泛流行,但是在國內還是MyBatis的天下。所以,今天這篇我們將具體說說如何在Spring Boot中整合MyBatis完成關系型數據庫的增刪改查操作。

    整合MyBatis

    第一步:新建Spring Boot項目,在pom.xml中引入MyBatis的Starter以及MySQL Connector依賴,具體如下:

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.1</version>
    </dependency>
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    

    關于mybatis-spring-boot-starter的版本需要注意:

    • 2.1.x版本適用于:MyBatis 3.5+、Java 8+、Spring Boot 2.1+
    • 2.0.x版本適用于:MyBatis 3.5+、Java 8+、Spring Boot 2.0/2.1
    • 1.3.x版本適用于:MyBatis 3.4+、Java 6+、Spring Boot 1.5

    其中,目前還在維護的是2.1.x版本和1.3.x版本。

    第二步:同之前介紹的使用jdbc模塊和jpa模塊連接數據庫一樣,在application.properties中配置mysql的連接配置

    spring.datasource.url=jdbc:mysql://localhost:3306/test
    spring.datasource.username=root
    spring.datasource.password=
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    

    當然,也可以不用默認數據源,如果要使用Druid作為數據庫連接池的話,可以參見《使用國產數據庫連接池Druid》一文。

    第三步:Mysql中創建一張用來測試的表,比如:User表,其中包含id(BIGINT)、age(INT)、name(VARCHAR)字段。

    具體創建命令如下:

    CREATE TABLE `User` (
      `id` bigint NOT NULL AUTO_INCREMENT,
      `name` varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL,
      `age` int DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
    

    第四步:創建User表的映射對象User:

    @Data
    @NoArgsConstructor
    public class User {
    
        private Long id;
    
        private String name;
        private Integer age;
    
        public User(String name, Integer age) {
            this.name = name;
            this.age = age;
        }
    }
    

    第五步:創建User表的操作接口:UserMapper。在接口中定義兩個數據操作,一個插入,一個查詢,用于后續單元測試驗證。

    @Mapper
    public interface UserMapper {
    
        @Select("SELECT * FROM USER WHERE NAME = #{name}")
        User findByName(@Param("name") String name);
    
        @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
        int insert(@Param("name") String name, @Param("age") Integer age);
    
    }
    
    

    第六步:創建Spring Boot主類

    @SpringBootApplication
    public class Chapter35Application {
    
    	public static void main(String[] args) {
    		SpringApplication.run(Chapter35Application.class, args);
    	}
    
    }
    

    第七步:創建單元測試。具體測試邏輯如下:

    • 插入一條name=AAA,age=20的記錄,然后根據name=AAA查詢,并判斷age是否為20
    • 測試結束回滾數據,保證測試單元每次運行的數據環境獨立
    @Slf4j
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class Chapter35ApplicationTests {
    
        @Autowired
        private UserMapper userMapper;
    
        @Test
        @Rollback
        public void test() throws Exception {
            userMapper.insert("AAA", 20);
            User u = userMapper.findByName("AAA");
            Assert.assertEquals(20, u.getAge().intValue());
        }
    
    }
    

    注解配置說明

    下面通過幾種不同傳參方式來實現前文中實現的插入操作,來學習一下MyBatis中常用的一些注解。

    使用@Param

    在之前的整合示例中我們已經使用了這種最簡單的傳參方式,如下:

    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);
    

    這種方式很好理解,@Param中定義的name對應了SQL中的#{name}age對應了SQL中的#{age}。

    使用Map

    如下代碼,通過Map<String, Object>對象來作為傳遞參數的容器:

    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
    int insertByMap(Map<String, Object> map);
    

    對于Insert語句中需要的參數,我們只需要在map中填入同名的內容即可,具體如下面代碼所示:

    Map<String, Object> map = new HashMap<>();
    map.put("name", "CCC");
    map.put("age", 40);
    userMapper.insertByMap(map);
    

    使用對象

    除了Map對象,我們也可直接使用普通的Java對象來作為查詢條件的傳參,比如我們可以直接使用User對象:

    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
    int insertByUser(User user);
    

    這樣語句中的#{name}#{age}就分別對應了User對象中的nameage屬性。

    增刪改查

    MyBatis針對不同的數據庫操作分別提供了不同的注解來進行配置,在之前的示例中演示了@Insert,下面針對User表做一組最基本的增刪改查作為示例:

    public interface UserMapper {
    
        @Select("SELECT * FROM user WHERE name = #{name}")
        User findByName(@Param("name") String name);
    
        @Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
        int insert(@Param("name") String name, @Param("age") Integer age);
    
        @Update("UPDATE user SET age=#{age} WHERE name=#{name}")
        void update(User user);
    
        @Delete("DELETE FROM user WHERE id =#{id}")
        void delete(Long id);
    }
    

    在完成了一套增刪改查后,不妨我們試試下面的單元測試來驗證上面操作的正確性:

    @Transactional
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class ApplicationTests {
    
    	@Autowired
    	private UserMapper userMapper;
    
    	@Test
    	@Rollback
    	public void testUserMapper() throws Exception {
    		// insert一條數據,并select出來驗證
    		userMapper.insert("AAA", 20);
    		User u = userMapper.findByName("AAA");
    		Assert.assertEquals(20, u.getAge().intValue());
    		// update一條數據,并select出來驗證
    		u.setAge(30);
    		userMapper.update(u);
    		u = userMapper.findByName("AAA");
    		Assert.assertEquals(30, u.getAge().intValue());
    		// 刪除這條數據,并select驗證
    		userMapper.delete(u.getId());
    		u = userMapper.findByName("AAA");
    		Assert.assertEquals(null, u);
    	}
    }
    

    返回結果綁定

    對于增、刪、改操作相對變化較小。而對于“查”操作,我們往往需要進行多表關聯,匯總計算等操作,那么對于查詢的結果往往就不再是簡單的實體對象了,往往需要返回一個與數據庫實體不同的包裝類,那么對于這類情況,就可以通過@Results@Result注解來進行綁定,具體如下:

    @Results({
        @Result(property = "name", column = "name"),
        @Result(property = "age", column = "age")
    })
    @Select("SELECT name, age FROM user")
    List<User> findAll();
    

    在上面代碼中,@Result中的property屬性對應User對象中的成員名,column對應SELECT出的字段名。在該配置中故意沒有查出id屬性,只對User對應中的name和age對象做了映射配置,這樣可以通過下面的單元測試來驗證查出的id為null,而其他屬性不為null:

    @Test
    @Rollback
    public void testUserMapper() throws Exception {
    	List<User> userList = userMapper.findAll();
    	for(User user : userList) {
    		Assert.assertEquals(null, user.getId());
    		Assert.assertNotEquals(null, user.getName());
    	}
    }
    

    注:本文轉載自“程序猿DD”,如有侵權,請聯系刪除!

    請登錄后查看

    哈哈哈醬 最后編輯于2024-12-20 16:37:05

    快捷回復
    回復
    回復
    回復({{post_count}}) {{!is_user ? '我的回復' :'全部回復'}}
    排序 默認正序 回復倒序 點贊倒序

    {{item.user_info.nickname ? item.user_info.nickname : item.user_name}} LV.{{ item.user_info.bbs_level }}

    作者 管理員 企業

    {{item.floor}}# 同步到gitee 已同步到gitee {{item.is_suggest == 1? '取消推薦': '推薦'}}
    {{item.is_suggest == 1? '取消推薦': '推薦'}}
    沙發 板凳 地板 {{item.floor}}#
    {{item.user_info.title || '暫無簡介'}}
    附件

    {{itemf.name}}

    {{item.created_at}}  {{item.ip_address}}
    打賞
    已打賞¥{{item.reward_price}}
    {{item.like_count}}
    {{item.showReply ? '取消回復' : '回復'}}
    刪除
    回復
    回復

    {{itemc.user_info.nickname}}

    {{itemc.user_name}}

    回復 {{itemc.comment_user_info.nickname}}

    附件

    {{itemf.name}}

    {{itemc.created_at}}
    打賞
    已打賞¥{{itemc.reward_price}}
    {{itemc.like_count}}
    {{itemc.showReply ? '取消回復' : '回復'}}
    刪除
    回復
    回復
    查看更多
    打賞
    已打賞¥{{reward_price}}
    1223
    {{like_count}}
    {{collect_count}}
    添加回復 ({{post_count}})

    相關推薦

    快速安全登錄

    使用微信掃碼登錄
    {{item.label}} 加精
    {{item.label}} {{item.label}} 板塊推薦 常見問題 產品動態 精選推薦 首頁頭條 首頁動態 首頁推薦
    取 消 確 定
    回復
    回復
    問題:
    問題自動獲取的帖子內容,不準確時需要手動修改. [獲取答案]
    答案:
    提交
    bug 需求 取 消 確 定
    打賞金額
    當前余額:¥{{rewardUserInfo.reward_price}}
    {{item.price}}元
    請輸入 0.1-{{reward_max_price}} 范圍內的數值
    打賞成功
    ¥{{price}}
    完成 確認打賞

    微信登錄/注冊

    切換手機號登錄

    {{ bind_phone ? '綁定手機' : '手機登錄'}}

    {{codeText}}
    切換微信登錄/注冊
    暫不綁定
    亚洲欧美字幕
    CRMEB客服

    CRMEB咨詢熱線 咨詢熱線

    400-8888-794

    微信掃碼咨詢

    CRMEB開源商城下載 源碼下載 CRMEB幫助文檔 幫助文檔
    返回頂部 返回頂部
    CRMEB客服