SpringBoot從入門到精通二(SpringBoot整合myBatis的兩種方式)

前言

經過上一章的學習,咱們已經對SpringBoot有簡單的入門,接下來咱們深刻學習一下SpringBoot,咱們知道任何一個網站的數據大多數都是動態的,也就是說數據是從數據庫提取出來的,而非靜態數據,那麼咱們接下來就是要鏈接數據,如今咱們常常使用的數據庫有MySQL數據庫,Oracle數據庫,Redis(非關係型數據庫),Mongodb(非關係型數據庫)等等。java

本章目標

1)學會使用SpringBoot和MyBatis經過註解的方式操做數據庫mysql

2)學會使用SpringBoot和MyBatis經過XML配置文件的方式操做數據庫web

項目搭建

1)打開idea,Create New Projectspring

2)選擇Spring Initializer,而後點擊下一步sql

3)填寫組織,座標等信息,而後點擊Next數據庫

4)選擇依賴Web,而後勾選Web,點擊Next,而後一直點擊Next,直到項目結構創建完成apache

5)項目結構搭好以後,咱們新建一些包有控制層,服務層,數據訪問層,實體層,完整結構以下mybatis

6)因爲咱們要使用MyBatis操做數據庫,因此須要添加一些依賴,完整的pom.xml文件以下app

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.demo02</groupId>
    <artifactId>demo_02</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo_02</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--mybatis-spring適配器-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!--mysql驅動包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

7)接下來咱們須要新建數據庫以及生成實體,數據的創建我就不重複多說了,說一下使用idea快速生成實體(Product),數據庫的sql腳本以下框架

#建立商品信息表
create  table product ( pid int primary key not null auto_increment COMMENT"商品編號", pname varchar(50) COMMENT"商品名稱", pprice DECIMAL(10,2) COMMENT"商品價格", ptime varchar(50) COMMENT"入庫時間", pcount int COMMENT"庫存", pstatus int COMMENT"商品狀態" #0 表明下架,1表明上架 )COMMENT"商品信息表" insert into product(pname,pprice,ptime,pcount,pstatus)VALUES ("蘋果",11,"2019-10-1",11,1) SELECT * from product

 

 

8)Database表示要鏈接的數據庫名稱,User表示用戶名稱,Password表示密碼,而後點擊Ok,而後選擇你要生成實體的目錄,生成完成以後基本結構就搭建好了

9)Product實體代碼以下

package com.ssm.entity;
/*
* 商品實體類
* */
public class Product { private long pid;//編號 private String pname;//名稱 private double pprice;//價格 private String ptime;//入庫時間 private long pcount;//數量 private long pstatus;//狀態 //無參構造方法 public Product() {} //帶參構造方法 public Product(long pid, String pname, double pprice, String ptime, long pcount, long pstatus) { this.pid = pid; this.pname = pname; this.pprice = pprice; this.ptime = ptime; this.pcount = pcount; this.pstatus = pstatus; } public long getPid() { return pid; } public void setPid(long pid) { this.pid = pid; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public double getPprice() { return pprice; } public void setPprice(double pprice) { this.pprice = pprice; } public String getPtime() { return ptime; } public void setPtime(String ptime) { this.ptime = ptime; } public long getPcount() { return pcount; } public void setPcount(long pcount) { this.pcount = pcount; } public long getPstatus() { return pstatus; } public void setPstatus(long pstatus) { this.pstatus = pstatus; } @Override public String toString() { return "Product{" + "pid=" + pid + ", pname='" + pname + '\'' + ", pprice=" + pprice + ", ptime='" + ptime + '\'' + ", pcount=" + pcount + ", pstatus=" + pstatus + '}'; } }

 

SpringBoot整合myBais方式一(註解方式)

1)接下來,咱們就須要配置一下鏈接數據庫的配置文件,在application.xml中進行配置,applicaion.xml文件以下

#鏈接數據庫的驅動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#鏈接數據庫的url
spring.datasource.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
#用戶名
spring.datasource.username=root
#密碼
spring.datasource.password=123456

2)如今咱們就能夠操做數據庫了,編寫ProductDao,ProductService,ProductImple,ProductController以及配置SpringBoot主程序,因爲咱們新建的包不是和SpringBoot主程序同級目錄,因此沒法掃描到(項目啓動時,只有@SpringBootApplication 所在的包被掃描,啓動類是MainApplication.java, 也就是MainApplication.java類所在的這個包,而其餘的controller和service以及mapper在其餘的包裏,因此並無被掃描)因此咱們須要配置一下

3)ProductDao文件以下

package com.ssm.dao;


import com.ssm.entity.Product; import org.apache.ibatis.annotations.Select; import java.util.List; public interface ProductDao { @Select("select * from product") List<Product> findAllProduct(); }

 

4)ProductService文件以下

package com.ssm.service;

import com.ssm.entity.Product; import java.util.List; public interface ProductService { List<Product> findAllProduct(); }

 

5)ProductImple文件以下

 

package com.ssm.service.imple;

import com.ssm.dao.ProductDao; import com.ssm.entity.Product; import com.ssm.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ProductImple implements ProductService { @Autowired private ProductDao productDao; @Override public List<Product> findAllProduct() { return productDao.findAllProduct(); } }

 

6)ProductController文件以下

package com.ssm.controller;

import com.ssm.entity.Product; import com.ssm.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class ProductController { @Autowired private ProductService productService; //查詢所有的商品信息 @GetMapping("/product") public List<Product> findAllProduct(){ return productService.findAllProduct(); } }

 

7)SpringBoot主程序文件以下

package com.demo02.demo_02;

import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan(basePackages = {"com.ssm.controller","com.ssm.service"}) @MapperScan(basePackages = {"com.ssm.dao"}) public class Demo02Application { public static void main(String[] args) { SpringApplication.run(Demo02Application.class, args); } }

 

8)點擊運行,在地址欄輸入localhost:8080/product,若是出現以下結果,那麼恭喜你,第一種方式你已經學會了

 

SpringBoot整合MyBatis方式二(XML配置文件)

1)如今咱們經過第二種方式操做數據庫,咱們先將application.xml中的配置文件所有註釋,而後新建applicaion.yml,爲何要使用這種格式呢?由於這種方式方便簡潔,官方也推薦咱們使用這種類型,這是一些的相關格式,

server:
   port: 8801
eureka:
   client:
     registerWithEureka: false
     fetchRegistry: false
     serviceUrl:
      defaultZone: http://localhost:8801/eureka/

2)applicaion.yml配置以下

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url:  jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
    username: root
    password: 123456
mybatis:
  typeAliasesPackage: com.ssm.entity
  mapperLocations:  classpath:mapper/*Mapper.xml

 

3)咱們要經過xml的格式操做數據庫也就是咱們須要寫Mapper.xml文件,在src/main/resources新建Mapper文件夾,而後新建ProductMapper.xml

 

4)ProductMapper.xml文件以下

<?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.ssm.dao.ProductDao">
    <!--查詢所有商品信息-->
    <select id="findAllProduct" resultType="product">
        select  * from product
    </select>
</mapper>

 

5)ProductDao文件以下

 

package com.ssm.dao;


import com.ssm.entity.Product; import org.apache.ibatis.annotations.Select; import java.util.List; public interface ProductDao { // @Select("select * from product") List<Product> findAllProduct(); }

 

6)ProductService文件以下

 

package com.ssm.service;

import com.ssm.entity.Product; import java.util.List; public interface ProductService { List<Product> findAllProduct(); }

 

7)ProductImple文件以下

 

package com.ssm.service.imple;

import com.ssm.dao.ProductDao; import com.ssm.entity.Product; import com.ssm.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ProductImple implements ProductService { @Autowired private ProductDao productDao; @Override public List<Product> findAllProduct() { return productDao.findAllProduct(); } }

 

8)ProductController文件以下

 

package com.ssm.controller;

import com.ssm.entity.Product; import com.ssm.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class ProductController { @Autowired private ProductService productService; //查詢所有的商品信息 @GetMapping("/product") public List<Product> findAllProduct(){ return productService.findAllProduct(); } }

 

9)SpringBoot主程序文件以下

 

package com.demo02.demo_02;

import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan(basePackages = {"com.ssm.controller","com.ssm.service"}) @MapperScan(basePackages = {"com.ssm.dao"}) public class Demo02Application { public static void main(String[] args) { SpringApplication.run(Demo02Application.class, args); } }

 

10)運行,結果和以前的同樣

 

總結

經過對本章的學習,咱們已經能夠操做數據庫了,相對SSM框架來講,SpringBoot的確簡化了咱們許多操做,當你須要哪些依賴時,咱們直接選擇就能夠,它也的確比較實在。也但願你們能夠和我多多交流。

相關文章
相關標籤/搜索