將Mybatis引入Spring Boot項目連接數據庫操作


將Mybatis引入Spring Boot項目連接數據庫操作

一,首先,在pom.xml引入Mybatis插件

加入Maven依賴代碼即可快速引入Mybatis 2.0.0:

<!--Mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>
<!--MySQL-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

上面代碼將mybatis 2.0.0和mysql連接插件引入項目,保存,等待插件加載完。

二,在配置文件中加入連接配置信息

打開application.properties編輯,加入連接配置信息:

#mybatis鏈接數據庫相關配置
spring.datasource.url=jdbc:mysql://192.168.10.223:3306/db_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=Kings0ft_01
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

以上信息用於連接mysql數據庫。

三,在項目啟動程序中加入mapper注解

打開項目的Xxhdemo1Application,加入注解。

package xxh.springbootmvc.xxhdemo1;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
/*Spring Boot 會自動加載 spring.datasource.* 相關配置,數據源就會自動注入到 sqlSessionFactory 中,
sqlSessionFactory 會自動注入到 Mapper 中*/
@MapperScan("xxh.springbootmvc.xxhdemo1.MybatisDemo.mapper")
public class Xxhdemo1Application {
    public static void main(String[] args) {
        SpringApplication.run(Xxhdemo1Application.class, args);
    }
}

注意,加入@MapperScan注解后,Spring Boot 會自動加載 spring.datasource.* 相關配置,數據源就會自動注入到 sqlSessionFactory 中,sqlSessionFactory 會自動注入到 Mapper 中。

四,按上面Mapper 路徑創建自己建Package,然后在里面創建自己的Mapper 和Model。

創建Model示例 D:\javaWorkspace\IdeaProjects\xxhdemo1\src\main\java\xxh\springbootmvc\xxhdemo1\MybatisDemo\mapper\UserEntity.java:

package xxh.springbootmvc.xxhdemo1.MybatisDemo.mapper;

import java.util.Date;

public class UserEntity {
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public String getDesc() {
        return Desc;
    }

    public void setDesc(String desc) {
        Desc = desc;
    }

    public Date getCreateTime() {
        return CreateTime;
    }

    public void setCreateTime(Date createTime) {
        CreateTime = createTime;
    }

    public UserEntity(int id, String name, String desc, Date createTime) {
        this.id = id;
        Name = name;
        Desc = desc;
        CreateTime = createTime;
    }

    @Override
    public String toString() {
        return "UserEntity{" +
                "id=" + id +
                ", Name='" + Name + '\'' +
                ", Desc='" + Desc + '\'' +
                ", CreateTime=" + CreateTime +
                '}';
    }

    private int id;
    private String Name;
    private String Desc;
    private Date CreateTime;
}

創建Mapper示例 D:\javaWorkspace\IdeaProjects\xxhdemo1\src\main\java\xxh\springbootmvc\xxhdemo1\MybatisDemo\mapper\UserMapper.java

package xxh.springbootmvc.xxhdemo1.MybatisDemo.mapper;

import org.apache.ibatis.annotations.*;
import java.util.List;
/*注意Mapper的類型是“接口”*/
public interface UserMapper {
    /*查詢操作示例*/
    @Select("SELECT * FROM t_user;")
    @Results({
            @Result(property = "id",  column = "Id"),
            @Result(property = "Name", column = "Name"),
            @Result(property = "Desc", column = "Desc"),
            @Result(property = "CreateTime", column = "CreateTime")
    })
    List<UserEntity> getAll();
    /*查詢操作示例*/
    @Select("SELECT * FROM t_user WHERE Id = #{id};")
    @Results({
            @Result(property = "id",  column = "Id"),
            @Result(property = "Name", column = "Name"),
            @Result(property = "Desc", column = "Desc"),
            @Result(property = "CreateTime", column = "CreateTime")
    })
    UserEntity getEntity(int id);
    /*插入操作示例*/
    @Insert("INSERT INTO t_user(`Name`,`Desc`,CreateTime) VALUES(#{Name}, #{Desc}, #{CreateTime});")
    @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="Id") /*將自增ID綁定到實體,keyProperty是實體字段,keyColumn是數據庫字段*/
    int insert(UserEntity user);
    /*修改操作示例*/
    @Update("UPDATE t_user SET `Name`=#{Name},`Desc`=#{Desc} WHERE Id =#{id};")
    int update(UserEntity user);
    /*刪除操作示例*/
    @Delete("DELETE FROM t_user WHERE Id =#{id};")
    int delete(int id);
}

 

五,創建Controller,寫接口或頁面調用操作數據庫方法

測試demo只需要放回數據即可,不寫頁面了。所以引入@RestController,@RequestMapping注解。然后必須在控制器域代碼里聲明Mapper類型,訪問類型一般是私有的:

/*在控制器域代碼聲明Mapper類型*/
private UserMapper UserMapper;

然后再控制器里面寫各種調用Mapper操作數據庫方法,調用正刪查改完整示例:

package xxh.springbootmvc.xxhdemo1.MybatisDemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xxh.springbootmvc.xxhdemo1.MybatisDemo.mapper.UserEntity;
import xxh.springbootmvc.xxhdemo1.MybatisDemo.mapper.UserMapper;
import java.util.List;
import java.util.Date;

@RestController
@EnableAutoConfiguration
@RequestMapping("/v1/mybatisdemo")
public class mysqlTestController {
    /*在控制器域代碼聲明Mapper類型*/
    @Autowired
    private UserMapper UserMapper;

    @RequestMapping("add")
    public int testInsert() throws Exception {
        int id, num = 0;
        UserEntity u = new UserEntity(0, "劉備", "大哥", new Date());
        num = UserMapper.insert(u);
        id = u.getId();
        System.out.println("新增數據完成 id=" + id + ",num=" + num);
        return num;
    }

    @RequestMapping("get")
    public UserEntity testQueryOne(int id) throws Exception {
        UserEntity UserEntity = UserMapper.getEntity(id);
        System.out.println(UserEntity.toString());
        return UserEntity;
    }

    @RequestMapping("getlist")
    public List<UserEntity> testQuery() throws Exception {
        List<UserEntity> UserEntitys = UserMapper.getAll();
        System.out.println(UserEntitys.toString());
        return UserEntitys;
    }

    @RequestMapping("edit")
    public int testUpdate(int id, String name, String desc) throws Exception {
        int num = 0;
        UserEntity UserEntity = UserMapper.getEntity(id);
        if (null != UserEntity && UserEntity.getId() > 0) {
            System.out.println(UserEntity.toString());
            UserEntity.setName(name);
            UserEntity.setDesc(desc);
            num = UserMapper.update(UserEntity);
        }
        return num;
    }

    @RequestMapping("del")
    public int testDelete(int id) throws Exception {
        int num = 0;
        if (id > 0) {
            num = UserMapper.delete(id);
        }
        return num;
    }
}

到這里就可以運行項目代碼,測試接口了。

代碼結構如圖:

 

 

六,創建MySQL數據庫及表結構

創建MySQL數據庫:

CREATE DATABASE IF NOT EXISTS db_demo DEFAULT CHARSET utf8mb4;

創建數據庫表結構:

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Name` varchar(255) DEFAULT NULL,
  `Desc` varchar(255) DEFAULT NULL,
  `CreateTime` datetime(3) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8mb4;

 

其中,查詢數據列表的運行效果,如圖:

 

 

【完】

 

上一篇:idea創建一個入門Spring Boot項目(controller層)使用Maven代碼管理

 下一篇:將Ldap組織結構及用戶信息同步到MySQL,用Spring Boot項目操作


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM