SpringCloud(第 043 篇)連接Mysql數據庫簡單的集成Mybatis框架訪問數據庫

SpringCloud(第 043 篇)連接Mysql數據庫簡單的集成Mybatis框架訪問數據庫

1、大體介紹

一、訪問數據庫,天然少不了一些持久化框架,而我自己也是Mybatis框架的支持者;
二、Mybatis是那種專一於sql的框架,對象映射以及輸入輸出都是由框架自動完成;
三、所以本章節就簡單小試牛刀嘗試下如何使用Mybatis持久化框架進行對數據的操做;

2、實現步驟

2.1 添加 maven 引用包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

	<artifactId>springms-provider-user-mysql-mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
	
    <parent>
        <groupId>com.springms.cloud</groupId>
        <artifactId>springms-spring-cloud</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
	
	<dependencies>
        <!-- 訪問數據庫模塊 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

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

        <!-- MYSQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- Mybatis依賴 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>

</project>

2.2 添加應用配置文件(springms-provider-user-mysql-mybatis\src\main\resources\application.yml)

server:
  port: 8325
spring:
  application:
    name: springms-provider-user-mysql-mybatis  #所有小寫


#####################################################################################################
# mysql 屬性配置
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://ip:3306/hmilyylimh
    username: username
    password: password
#  jpa:
#    hibernate:
#      #ddl-auto: create #ddl-auto:設爲create表示每次都從新建表
#      ddl-auto: update #ddl-auto:設爲update表示每次都不會從新建表
#    show-sql: true
#####################################################################################################


#####################################################################################################
# 打印日誌
logging:
  level:
    root: INFO
    org.hibernate: INFO
    org.hibernate.type.descriptor.sql.BasicBinder: TRACE
    org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
    com.springms: DEBUG
#####################################################################################################

2.3 添加實體用戶類User(springms-provider-user-mysql-mybatis/src/main/java/com/springms/cloud/entity/User.java)

package com.springms.cloud.entity;


import javax.persistence.*;

/**
 *
 * Mybatis 須要加上這些註解纔可使用,否則啓動都會報錯;
 *
 */
@Entity
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @Column
  private String username;

  @Column
  private String name;

  @Column
  private Integer age;

  @Column
  private String balance;

  public Long getId() {
    return this.id;
  }

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

  public String getUsername() {
    return this.username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getName() {
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Integer getAge() {
    return this.age;
  }

  public void setAge(Integer age) {
    this.age = age;
  }

  public String getBalance() {
    return this.balance;
  }

  public void setBalance(String balance) {
    this.balance = balance;
  }
}

2.4 添加用戶mapper接口(springms-provider-user-mysql-mybatis/src/main/java/com/springms/cloud/mapper/IUserMapper.java)

package com.springms.cloud.mapper;

import com.springms.cloud.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 用戶 mybatis 映射文件。
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017-10-19
 *
 */
public interface IUserMapper {

    @Select("select * from user where id = #{id}")
    User findUserById(Long id);

    @Select("select * from user")
    List<User> findAllUsers();

    @Insert("INSERT INTO user(username, name, age, balance) VALUES(#{username}, #{name}, #{age}, #{balance})")
    int insertUser(User user);
}

2.5 添加用戶mapper接口實現類(springms-provider-user-mysql-mybatis/src/main/java/com/springms/cloud/mapper/user/UserMapper.java)

package com.springms.cloud.mapper.user;

/**
 *
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017-10-19
 *
 */
public class UserMapper {
}

2.6 添加用戶Service接口類(springms-provider-user-mysql-mybatis/src/main/java/com/springms/cloud/service/IUserService.java)

package com.springms.cloud.service;

import com.springms.cloud.entity.User;

import java.util.List;

/**
 * 簡單用戶連接Mysql數據庫微服務(經過@Service註解標註該類爲持久化操做對象)。
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017-10-19
 *
 */
public interface IUserService {

    User findUserById(Long id);

    List<User> findAllUsers();

    int insertUser(User user);
}

2.7 添加用戶Service接口實現類(springms-provider-user-mysql-mybatis/src/main/java/com/springms/cloud/service/impl/UserServiceImpl.java)

package com.springms.cloud.service.impl;

import com.springms.cloud.entity.User;
import com.springms.cloud.mapper.IUserMapper;
import com.springms.cloud.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 簡單用戶連接Mysql數據庫微服務(經過@Service註解標註該類爲持久化操做對象)。
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017-10-19
 *
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    IUserMapper iUserMapper;

    @Override
    public User findUserById(Long id) {
        return iUserMapper.findUserById(id);
    }

    @Override
    public List<User> findAllUsers() {
        return iUserMapper.findAllUsers();
    }

    @Override
    public int insertUser(User user) {
        return iUserMapper.insertUser(user);
    }
}

2.8 添加用戶Web訪問層Controller(springms-provider-user-mysql-mybatis/src/main/java/com/springms/cloud/controller/ProviderUserMysqlMybatisController.java)

package com.springms.cloud.controller;

import com.springms.cloud.entity.User;
import com.springms.cloud.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用戶微服務Controller。
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017-10-19
 *
 */
@RestController
public class ProviderUserMysqlMybatisController {

    @Autowired
    private IUserService iUserService;

    @GetMapping("/simple/{id}")
    public User findUserById(@PathVariable Long id) {
        return this.iUserService.findUserById(id);
    }

    @GetMapping("/simple/list")
    public List<User> findUserList() {
        return this.iUserService.findAllUsers();
    }

    /**
     * 添加一個student,使用postMapping接收post請求
     *
     * http://localhost:8310/simple/addUser?username=user11&age=11&balance=11
     *
     * @return
     */
    @PostMapping("/simple/addUser")
    public User addUser(@RequestParam(value = "username", required=false) String username, @RequestParam(value = "age", required=false) Integer age, @RequestParam(value = "balance", required=false) String balance){
        User user=new User();

        user.setUsername(username);
        user.setName(username);
        user.setAge(age);
        user.setBalance(balance);

        int result = iUserService.insertUser(user);
        if(result > 0){
            return user;
        }

        user.setId(0L);
        user.setName(null);
        user.setUsername(null);
        user.setBalance(null);
        return user;
    }
}

2.9 添加微服務啓動類(springms-provider-user-mysql-mybatis/src/main/java/com/springms/cloud/MsProviderUserMysqlMybatisApplication.java)

package com.springms.cloud;

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

/**
 * 連接Mysql數據庫簡單的集成Mybatis框架訪問數據庫。
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2017-10-19
 *
 */
@SpringBootApplication
@MapperScan("com.springms.cloud.mapper.**")
public class MsProviderUserMysqlMybatisApplication {

	public static void main(String[] args) {
		SpringApplication.run(MsProviderUserMysqlMybatisApplication.class, args);
		System.out.println("【【【【【【 連接MysqlMybatis數據庫微服務 】】】】】】已啓動.");
	}
}

3、測試

/****************************************************************************************
 注意:Mybatis 須要加上 entity 等註解纔可使用,否則啓動都會報錯;
 @MapperScan("com.springms.cloud.mapper.**") 或者在每一個 Mapper 接口文件上添加 @Mapper 也能夠;

 1、簡單用戶連接Mysql數據庫微服務(經過 mybatis 連接 mysql 編寫數據訪問):

 一、啓動 springms-provider-user-mysql-mybatis 模塊服務,啓動1個端口;
 二、在瀏覽器輸入地址 http://localhost:8325/simple/10 能夠看到用戶ID=10的信息成功的被打印出來;

 三、使用 IDEA 自帶工具 Test Restful WebService 發送 HTTP POST 請求,並添加 username、age、balance三個參數,而後執行請求,並去 mysql 數據庫查看數據是否存在,正常狀況下 mysql 數據庫剛剛插入的數據成功了:
 四、使用 REST Client 執行 "/simple/list" 接口,也正常將 mysql 數據庫中全部的用戶信息打印出來了;
 ****************************************************************************************/

4、下載地址

https://gitee.com/ylimhhmily/SpringCloudTutorial.gitjava

SpringCloudTutorial交流QQ羣: 235322432mysql

SpringCloudTutorial交流微信羣: 微信溝通羣二維碼圖片連接git

歡迎關注,您的確定是對我最大的支持!!!web

相關文章
相關標籤/搜索