内射老阿姨1区2区3区4区_久久精品人人做人人爽电影蜜月_久久国产精品亚洲77777_99精品又大又爽又粗少妇毛片

SpringBoot數(shù)據(jù)訪問之Mybatis的示例分析

這篇文章主要介紹Spring Boot數(shù)據(jù)訪問之Mybatis的示例分析,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

創(chuàng)新互聯(lián)建站長期為千余家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺(tái),與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為紅寺堡企業(yè)提供專業(yè)的做網(wǎng)站、成都網(wǎng)站設(shè)計(jì),紅寺堡網(wǎng)站改版等技術(shù)服務(wù)。擁有10年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。

一、什么是MyBatis

  1. 支持定制化SQL、存儲(chǔ)過程以及高級(jí)映射的優(yōu)秀的持久層框架
  2. 避免了幾乎所有的 JDBC 代碼和手動(dòng)設(shè)置參數(shù)以及獲取結(jié)果集
  3. 可以對(duì)配置和原生Map使用簡單的 XML 或注解
  4. 將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對(duì)象)映射成數(shù)據(jù)庫中的記錄
  5. 數(shù)據(jù)庫、數(shù)據(jù)源、數(shù)據(jù)庫連接池、JDBC、JDBC實(shí)現(xiàn)是什么關(guān)系?

Spring Boot數(shù)據(jù)訪問之Mybatis的示例分析

  • JDBC:Java和關(guān)系型數(shù)據(jù)庫的橋梁,是一個(gè)規(guī)范,不是實(shí)現(xiàn)。不同類型的數(shù)據(jù)庫需要有自己的JDBC實(shí)現(xiàn)

  • 數(shù)據(jù)源:包含數(shù)據(jù)庫連接池,連接池管理。常見的有C3P0、HikariDataSoiurce、Druid等

  • 連接池:預(yù)先創(chuàng)建一些數(shù)據(jù)庫連接,放到連接池里面,用的時(shí)候從連接池里面取,用完后放回連接池

  • 連接池管理:創(chuàng)建數(shù)據(jù)庫連接,管理數(shù)據(jù)庫連接

  • JDBC實(shí)現(xiàn):MySQL JDBC實(shí)現(xiàn)、Oracle JDBC實(shí)現(xiàn)等其他實(shí)現(xiàn)

  • MyBatis對(duì)JDBC進(jìn)行了封裝

二、整合MyBatis

我們基于之前創(chuàng)建的項(xiàng)目spring-boot-06-data-druid 來創(chuàng)建spring-boot-07-data-mybatis項(xiàng)目

1)引入MyBatis依賴

<!-- mybatis -->
<dependency>
 <groupId>org.mybatis.spring.boot</groupId>
 <artifactId>mybatis-spring-boot-starter</artifactId>
 <version>2.1.1</version>
</dependency>

2)引入其他依賴

<dependencies>
 <!-- web -->
 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

 <!-- mysql -->
 <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
 </dependency>

 <!-- swagger -->
 <dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.9.2</version>
 </dependency>
 <dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.9.2</version>
 </dependency>

 <!-- Druid -->
 <dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.1.21</version>
 </dependency>

3)依賴圖

Spring Boot數(shù)據(jù)訪問之Mybatis的示例分析

三、用注解方式使用 MyBatis

1.準(zhǔn)備創(chuàng)建department表的腳本

DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `department_name` varchar(255) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

2.application.yml 自動(dòng)執(zhí)行腳本

initialization-mode: always
schema:
 - classpath:department.sql

執(zhí)行一次后,注釋 initialization-mode

# initialization-mode: always

3.創(chuàng)建department 實(shí)體類

package com.jackson0714.springboot.entity;
public class Department {    private Long id;    private String departmentName;
   public void setId(Long id) {        this.id = id;    }
   public Long getId() {        return id;    }
   public void setDepartmentName(String departmentName) {        this.departmentName = departmentName;    }
   public String getDepartmentName() {        return departmentName;    }}

4.創(chuàng)建Mapper映射類,并將SQL注解到方法上

增刪改查,你要的都在這里:

@Mapperpublic interface DepartmentMapper {
   @Select("select * from department")    List<Map<String, Object>> getAllDepartment();
   @Select("select * from department where id=#{id}")    Department getDepartmentById(Long id);
   @Delete("delete from department where id=#{id}")    int deleteDepartment(Long id);
   @Insert("insert into department(department_name) values(#{departmentName})")    int createDepartment(String departmentName);
   @Update("update department set department_name=#{departmentName} where id=#{id}")    int updateDepartmentById(Long id, String departmentName);}

5.創(chuàng)建MyBatis 配置類

增加自定義配置:如果表的字段名有下劃線格式的,轉(zhuǎn)為駝峰命名格式

@org.springframework.context.annotation.Configurationpublic class MyBatisConfig {    @Bean    public ConfigurationCustomizer configurationCustomizer() {        return new ConfigurationCustomizer() {            @Override            public void customize(Configuration configuration) {                // 如果表的字段名有下劃線格式的,轉(zhuǎn)為駝峰命名格式                configuration.setMapUnderscoreToCamelCase(true);            }        };    }}

6.創(chuàng)建DepartmentController

@Api(value = "DepartmentController", description = "部門controller")@RequestMapping("/v1/client")@RestControllerpublic class DepartmentController {
   @Autowired    DepartmentMapper departmentMapper;
   @ApiOperation(value = "1.查詢所有部門")    @GetMapping("/dept/getAllDepartment")    public List<Map<String, Object>> getAllDepartment() {        return departmentMapper.getAllDepartment();    }
   @ApiOperation(value = "2.根據(jù)id查詢某個(gè)部門")    @ApiImplicitParams({            @ApiImplicitParam(name = "id", value = "需要查詢的部門id")    })    @GetMapping("/dept/{id}")    public Department getDepartmentById(@PathVariable Long id) {        return departmentMapper.getDepartmentById(id);    }
   @ApiOperation(value = "3.新增部門")    @ApiImplicitParams({            @ApiImplicitParam(name = "name", value = "部門名稱")    })    @PostMapping("/dept/create")    public int createDepartment(@RequestParam String name) {        return departmentMapper.createDepartment(name);    }
   @ApiOperation(value = "4.根據(jù)id刪除部門")    @ApiImplicitParams({            @ApiImplicitParam(name = "id", value = "需要?jiǎng)h除的部門id")    })    @PostMapping("/dept/delete")    public int deleteDepartment(@RequestParam Long id) {        return departmentMapper.deleteDepartment(id);    }
   @ApiOperation(value = "5.根據(jù)id更新部門名稱")    @ApiImplicitParams({            @ApiImplicitParam(name = "id", value = "需要更新的部門id"),            @ApiImplicitParam(name = "name", value = "需要更新的部門名稱")    })    @PostMapping("/dept/update")    public int updateDepartmentById(@RequestParam Long id, @RequestParam String name) {        return departmentMapper.updateDepartmentById(id, name);    }}

使用Swagger來測(cè)試

Spring Boot數(shù)據(jù)訪問之Mybatis的示例分析

四、用配置方式使用 MyBatis

1. 文件結(jié)構(gòu)

Spring Boot數(shù)據(jù)訪問之Mybatis的示例分析

2. 創(chuàng)建user表的腳本

SET FOREIGN_KEY_CHECKS=0;
-- ------------------------------ Table structure for user-- ----------------------------DROP TABLE IF EXISTS `user`;CREATE TABLE `user` (  `user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵ID',  `user_name` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '用戶名',  `password` varchar(255) COLLATE utf8mb4_bin NOT NULL,  `salt` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '隨機(jī)鹽',  `nickName` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '用戶名',  `phone` varchar(20) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '手機(jī)號(hào)',  `avatar` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '頭像',  `mini_openId`  varchar(32) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '小程序OpenId',  `lock_flag` char(1) COLLATE utf8mb4_bin DEFAULT '0' COMMENT '0-正常,9-鎖定',  `del_flag` char(1) COLLATE utf8mb4_bin DEFAULT '0' COMMENT '0-正常,1-刪除',  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時(shí)間',  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時(shí)間',  PRIMARY KEY (`user_id`),  KEY `user_wx_openid` (`mini_openId`),  KEY `user_idx1_username` (`user_name`)) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='用戶表';

3. 插入一條User數(shù)據(jù)

INSERT INTO user(user_name, password, nick_name, phone) values ("jackson0714", "123", "悟空聊架構(gòu)", "123456")

4. 創(chuàng)建User實(shí)體類

package com.jackson0714.springboot.entity;
import lombok.Data;
import java.sql.Timestamp;
@Datapublic class User {
   private Long userId;    private String userName;    private String password;    private String salt;    private String nickName;    private String phone;    private String avatar;    private String miniOpenId;    private String openId;    private Boolean lockFlag;    private Boolean delFlag;    private Timestamp createTime;    private Timestamp updateTime;}

需要安裝Lombok插件

Spring Boot數(shù)據(jù)訪問之Mybatis的示例分析

需要引入Lombok依賴

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
 <groupId>org.projectlombok</groupId>
 <artifactId>lombok</artifactId>
 <version>1.18.12</version>
 <scope>provided</scope>
</dependency>

5. 創(chuàng)建調(diào)用User方法的 UserMapper 接口

// @Mapper 或MapperScan 將接口掃描裝配到裝配容器中
public interface UserMapper {
   User getUserById(Long userId);
}

6. 創(chuàng)建接口方法與SQL腳本的映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
       PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jackson0714.springboot.mapper.UserMapper">
   <select id="getUserById" resultType="com.jackson0714.springboot.entity.User">
       SELECT * FROM user WHERE user_id=#{userId}
   </select>
</mapper>

7. 創(chuàng)建UserController文件

@Api(value = "UserController", description = "用戶controller")@RequestMapping("/v1/client")@RestControllerpublic class UserController {
   @Autowired    UserMapper userMapper;
   @ApiOperation(value = "1.根據(jù)id查詢某個(gè)用戶")    @ApiImplicitParams({            @ApiImplicitParam(name = "需要查詢的用戶userId", value = "需要查詢的用戶userId")    })    @GetMapping("/emp/{userId}")    public User getUser(@PathVariable("userId") Long userId) {        return userMapper.getUserById(userId);    }}

8. 添加MapperScan注解

@MapperScan(value = "com.jackson0714.springboot.mapper")@SpringBootApplicationpublic class Springboot07DataMybatisApplication {    public static void main(String[] args) {        SpringApplication.run(Springboot07DataMybatisApplication.class, args);    }}

9.在Swagger上測(cè)試

Spring Boot數(shù)據(jù)訪問之Mybatis的示例分析

10. 查看Druid監(jiān)控

Spring Boot數(shù)據(jù)訪問之Mybatis的示例分析

代碼下載:

https://github.com/Jackson0714/study-spring-boot.git

以上是“Spring Boot數(shù)據(jù)訪問之Mybatis的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

本文題目:SpringBoot數(shù)據(jù)訪問之Mybatis的示例分析
網(wǎng)站地址:http://www.rwnh.cn/article20/ghcico.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、服務(wù)器托管、營銷型網(wǎng)站建設(shè)、、搜索引擎優(yōu)化、網(wǎng)站策劃

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作
平阴县| 化州市| 景宁| 闸北区| 晋中市| 沁源县| 繁峙县| 峨眉山市| 政和县| 石景山区| 金山区| 无棣县| 运城市| 丽江市| 乐山市| 咸宁市| 平安县| 辉南县| 洪雅县| 休宁县| 陵水| 通海县| 苍山县| 镇巴县| 衡阳市| 景宁| 怀仁县| 浑源县| 大余县| 安化县| 浦北县| 维西| 通河县| 奉节县| 武冈市| 原平市| 铁岭县| 新干县| 武川县| 阿拉善左旗| 延安市|