<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Spring Boot入門系列(十八)mybatis 使用注解實(shí)現(xiàn)增刪改查,無(wú)需xml文件!

          共 9790字,需瀏覽 20分鐘

           ·

          2020-08-20 12:05

          之前介紹了Spring Boot 整合mybatis 使用xml配置的方式實(shí)現(xiàn)增刪改查,還介紹了自定義mapper 實(shí)現(xiàn)復(fù)雜多表關(guān)聯(lián)查詢。雖然目前 mybatis 使用xml 配置的方式 已經(jīng)極大減輕了配置的復(fù)雜度,支持 generator 插件 根據(jù)表結(jié)構(gòu)自動(dòng)生成實(shí)體類、配置文件和dao層代碼,減輕很大一部分開發(fā)量;但是 java 注解的運(yùn)用發(fā)展到今天。約定取代配置的規(guī)范已經(jīng)深入人心。開發(fā)者還是傾向于使用注解解決一切問題,注解版最大的特點(diǎn)是具體的 SQL 文件需要寫在 Mapper 類中,取消了 Mapper 的 XML 配置 。這樣不用任何配置文件,就可以簡(jiǎn)單配置輕松上手。所以今天就介紹Spring Boot 整合mybatis 使用注解的方式實(shí)現(xiàn)數(shù)據(jù)庫(kù)操作 。

          Spring Boot 整合mybatis 使用xml配置版之前已經(jīng)介紹過(guò)了,不清楚的朋友可以看看之前的文章:《Spring Boot入門系列(十一)如何整合Mybatis,實(shí)現(xiàn)增刪改查【XML 配置版】》。

          ?

          一、整合Mybatis

          Spring Boot ?整合Mybatis 的步驟都是一樣的,已經(jīng)熟悉的同學(xué)可以略過(guò)。

          1、pom.xml增加mybatis相關(guān)依賴

          我們只需要加上pom.xml文件這些依賴即可。

                  <dependency>            <groupId>mysqlgroupId>            <artifactId>mysql-connector-javaartifactId>            <version>5.1.41version>        dependency>                <dependency>            <groupId>org.mybatis.spring.bootgroupId>            <artifactId>mybatis-spring-boot-starterartifactId>            <version>1.3.1version>        dependency>                <dependency>            <groupId>tk.mybatisgroupId>            <artifactId>mapper-spring-boot-starterartifactId>            <version>1.2.4version>        dependency>                <dependency>            <groupId>com.github.pagehelpergroupId>            <artifactId>pagehelper-spring-boot-starterartifactId>            <version>1.2.3version>        dependency>                <dependency>            <groupId>com.alibabagroupId>            <artifactId>druid-spring-boot-starterartifactId>            <version>1.1.9version>        dependency>        <dependency>            <groupId>org.mybatis.generatorgroupId>            <artifactId>mybatis-generator-coreartifactId>            <version>1.3.2version>            <scope>compilescope>            <optional>trueoptional>        dependency>

          ?

          2、application.properties配置數(shù)據(jù)連接

          application.properties 中需要增加 mybatis 相關(guān)的數(shù)據(jù)庫(kù)配置。

          ############################################################# 數(shù)據(jù)源相關(guān)配置,這里用的是阿里的druid 數(shù)據(jù)源############################################################spring.datasource.url=jdbc:mysql://localhost:3306/zwz_testspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.druid.initial-size=1spring.datasource.druid.min-idle=1spring.datasource.druid.max-active=20spring.datasource.druid.test-on-borrow=truespring.datasource.druid.stat-view-servlet.allow=true
          ############################################################# mybatis 相關(guān)配置############################################################mybatis.type-aliases-package=com.weiz.pojomybatis.mapper-locations=classpath:mapper/*.xmlmapper.mappers=com.weiz.utils.MyMapper #這個(gè)MyMapper 就是我之前創(chuàng)建的mapper統(tǒng)一接口。后面所有的mapper類都會(huì)繼承這個(gè)接口mapper.not-empty=falsemapper.identity=MYSQL# 分頁(yè)框架pagehelper.helperDialect=mysqlpagehelper.reasonable=truepagehelper.supportMethodsArguments=truepagehelper.params=count=countSql

          這里的配置有點(diǎn)多,不過(guò)最基本的配置都在這。


          3、在啟動(dòng)主類添加掃描器


          @SpringBootApplication//掃描 mybatis mapper 包路徑@MapperScan(basePackages = "com.weiz.mapper") // 這一步別忘了。//掃描 所有需要的包, 包含一些自用的工具類包 所在的路徑@ComponentScan(basePackages = {"com.weiz","org.n3r.idworker"})public class SpringBootStarterApplication {
          public static void main(String[] args) { SpringApplication.run(SpringBootStarterApplication.class, args); }
          }

          在SpringBootStarterApplication 啟動(dòng)類中增加包掃描器。

          注意:這一步別忘了,需要在SpringBootStarterApplication 啟動(dòng)類中增加包掃描器,自動(dòng)掃描加載com.weiz.mapper 里面的mapper 類。

          ?

          以上,就把Mybatis 整合到項(xiàng)目中了。?接下來(lái)就是創(chuàng)建表和pojo類,mybatis提供了強(qiáng)大的自動(dòng)生成功能。只需簡(jiǎn)單幾步就能生成pojo 類和mapper。

          ?

          二、代碼自動(dòng)生成工具

          Mybatis 整合完之后,接下來(lái)就是創(chuàng)建表和pojo類,mybatis提供了強(qiáng)大的自動(dòng)生成功能的插件。mybatis generator插件只需簡(jiǎn)單幾步就能生成pojo 類和mapper。操作步驟和xml 配置版也是類似的,唯一要注意的是?generatorConfig.xml?的部分配置,要配置按注解的方式生成mapper 。

          1、增加generatorConfig.xml配置文件

          在resources 文件下創(chuàng)建 generatorConfig.xml 文件。此配置文件獨(dú)立于項(xiàng)目,只是給自動(dòng)生成工具類的配置文件,具體配置如下:

                  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration>    <context id="DB2Tables"  targetRuntime="MyBatis3">        <commentGenerator>            <property name="suppressDate" value="true"/>                        <property name="suppressAllComments" value="true"/>        commentGenerator>                <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/zwz_test" userId="root" password="root">        jdbcConnection>        <javaTypeResolver>            <property name="forceBigDecimals" value="false"/>        javaTypeResolver>                <javaModelGenerator targetPackage="com.weiz.pojo" targetProject="src/main/java">            <property name="enableSubPackages" value="true"/>            <property name="trimStrings" value="true"/>        javaModelGenerator>                <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">            <property name="enableSubPackages" value="true"/>        sqlMapGenerator>                        <javaClientGenerator type="ANNOTATEDMAPPER" targetPackage="com.weiz.mapper" targetProject="src/main/java">            <property name="enableSubPackages" value="true"/>        javaClientGenerator>                <table tableName="sys_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">table>    context>generatorConfiguration>

          注意:

          這里的配置

          type 的值很重要:
            XMLMAPPER :表示生成xml映射文件。

            ANNOTATEDMAPPER:表示生成的mapper 采用注解來(lái)寫sql。

          ?

          2、數(shù)據(jù)庫(kù)User表

          需要在數(shù)據(jù)庫(kù)中創(chuàng)建相應(yīng)的表。這個(gè)表結(jié)構(gòu)很簡(jiǎn)單,就是普通的用戶表sys_user。

          CREATE TABLE `sys_user` (  `id` varchar(32) NOT NULL DEFAULT '',  `username` varchar(32) DEFAULT NULL,  `password` varchar(64) DEFAULT NULL,  `nickname` varchar(64) DEFAULT NULL,  `age` int(11) DEFAULT NULL,  `sex` int(11) DEFAULT NULL,  `job` int(11) DEFAULT NULL,  `face_image` varchar(6000) DEFAULT NULL,  `province` varchar(64) DEFAULT NULL,  `city` varchar(64) DEFAULT NULL,  `district` varchar(64) DEFAULT NULL,  `address` varchar(255) DEFAULT NULL,  `auth_salt` varchar(64) DEFAULT NULL,  `last_login_ip` varchar(64) DEFAULT NULL,  `last_login_time` datetime DEFAULT NULL,  `is_delete` int(11) DEFAULT NULL,  `regist_time` datetime DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;

          ?

          3、創(chuàng)建GeneratorDisplay類

          package com.weiz.utils;
          import java.io.File;import java.util.ArrayList;import java.util.List;
          import org.mybatis.generator.api.MyBatisGenerator;import org.mybatis.generator.config.Configuration;import org.mybatis.generator.config.xml.ConfigurationParser;import org.mybatis.generator.internal.DefaultShellCallback;
          public class GeneratorDisplay {
          public void generator() throws Exception{
          List warnings = new ArrayList(); boolean overwrite = true; //指定 逆向工程配置文件 File configFile = new File("generatorConfig.xml"); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null);
          } public static void main(String[] args) throws Exception { try { GeneratorDisplay generatorSqlmap = new GeneratorDisplay(); generatorSqlmap.generator(); } catch (Exception e) { e.printStackTrace(); } }}

          這其實(shí)也是調(diào)用mybatis generator實(shí)現(xiàn)的。跟mybatis generator安裝插件是一樣的。

          注意:利用Generator自動(dòng)生成代碼,對(duì)于已經(jīng)存在的文件會(huì)存在覆蓋和在原有文件上追加的可能性,不宜多次生成。如需重新生成,需要?jiǎng)h除已生成的源文件。

          ?

          4、Mybatis Generator自動(dòng)生成pojo和mapper

          運(yùn)行GeneratorDisplay 如下圖所示,即可自動(dòng)生成相關(guān)的代碼。

          ?

          ?

          上圖可以看到,pojo 包里面自動(dòng)生成了User 實(shí)體對(duì)象 ,mapper包里面生成了 UserMapper 和UserSqlProvider 類。UserMapper 是所有方法的實(shí)現(xiàn)。UserSqlProvider則是為UserMapper 實(shí)現(xiàn)動(dòng)態(tài)SQL。

          注意:

            UserMapper 中的所有的動(dòng)態(tài)SQL腳本,都定義在類UserSqlProvider中。若要增加新的動(dòng)態(tài)SQL,只需在UserSqlProvider中增加相應(yīng)的方法,然后在UserMapper中增加相應(yīng)的引用即可,

            如:@UpdateProvider(type=UserSqlProvider.class, method="updateByPrimaryKeySelective")。

          ?

          ?

          三、實(shí)現(xiàn)增刪改查

          在項(xiàng)目中整合了Mybatis并通過(guò)自動(dòng)生成工具生成了相關(guān)的mapper和配置文件之后,下面就開始項(xiàng)目中的調(diào)用。這個(gè)和之前的xml 配置版也是一樣的。

          1、在service包下創(chuàng)建UserService及UserServiceImpl接口實(shí)現(xiàn)類

          創(chuàng)建com.weiz.service包,添加UserService接口類

          package com.weiz.service;
          import com.weiz.pojo.User;
          public interface UserService { public int saveUser(User user); public int updateUser(User user); public int deleteUser(String userId); public User queryUserById(String userId);}

          創(chuàng)建com.weiz.service.impl包,并增加UserServiceImpl實(shí)現(xiàn)類,并實(shí)現(xiàn)增刪改查的功能,由于這個(gè)代碼比較簡(jiǎn)單,這里直接給出完整的代碼。

          package com.weiz.service.impl;
          import com.weiz.mapper.UserMapper;import com.weiz.pojo.User;import com.weiz.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;
          @Servicepublic class UserServiceImpl implements UserService {
          @Autowired private UserMapper userMapper;
          @Override public int saveUser(User user) { return userMapper.insertSelective(user); }
          @Override public int updateUser(User user) { return userMapper.updateByPrimaryKeySelective(user); }
          @Override public int deleteUser(String userId) { return userMapper.deleteByPrimaryKey(userId); }
          @Override public User queryUserById(String userId) { return userMapper.selectByPrimaryKey(userId); }}

          ?

          2、編寫controller層,增加MybatisController控制器

          package com.weiz.controller;
          import com.weiz.pojo.User;import com.weiz.utils.JSONResult;import com.weiz.service.UserService;import org.n3r.idworker.Sid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
          import java.util.Date;
          @RestController@RequestMapping("mybatis")public class MyBatisCRUDController {
          @Autowired private UserService userService;
          @Autowired private Sid sid;
          @RequestMapping("/saveUser") public JSONResult saveUser() {
          String userId = sid.nextShort(); User user = new User(); user.setId(userId); user.setUsername("spring boot" + new Date()); user.setNickname("spring boot" + new Date()); user.setPassword("abc123"); user.setIsDelete(0); user.setRegistTime(new Date());
          userService.saveUser(user); return JSONResult.ok("保存成功"); }
          @RequestMapping("/updateUser") public JSONResult updateUser() { User user = new User(); user.setId("10011001"); user.setUsername("10011001-updated" + new Date()); user.setNickname("10011001-updated" + new Date()); user.setPassword("10011001-updated"); user.setIsDelete(0); user.setRegistTime(new Date());
          userService.updateUser(user); return JSONResult.ok("保存成功"); }

          @RequestMapping("/deleteUser") public JSONResult deleteUser(String userId) { userService.deleteUser(userId); return JSONResult.ok("刪除成功"); }
          @RequestMapping("/queryUserById") public JSONResult queryUserById(String userId) { return JSONResult.ok(userService.queryUserById(userId)); }}

          ?

          3、測(cè)試

          在瀏覽器輸入controller里面定義的路徑即可。只要你按照上面的步驟一步一步來(lái),基本上就沒問題,是不是特別簡(jiǎn)單。

          ?

          ?

          最后

          以上,就把Spring Boot整合Mybatis注釋版 實(shí)現(xiàn)增刪改查介紹完了,Spring Boot 整合Mybatis 是整個(gè)Spring Boot 非常重要的功能,也是非常核心的基礎(chǔ)功能,希望大家能夠熟練掌握。后面會(huì)深入介紹Spring Boot的各個(gè)功能和用法。

          這個(gè)系列課程的完整源碼,也會(huì)提供給大家。大家關(guān)注我的微信公眾號(hào)(架構(gòu)師精進(jìn)),回復(fù):springboot源碼。獲取這個(gè)系列課程的完整源碼。



          推薦閱讀:




          瀏覽 62
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  国产精品二区高清在线苍井空 | 欧美15p色图 | 美女网站黄a | 天天干夜夜骑 | 日欧操逼小电影 |