1. 程式人生 > >SpringBoot--05.SpringBoot2.0學習小結

SpringBoot--05.SpringBoot2.0學習小結

1、SpringBoot2.0學習小結

用springBoot建立專案時、只關注三點:《啟動器》、《全域性屬性》、《啟動類》

(1)、啟動器 : pom.xml配置依賴
父工程座標

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>

新增web啟動器

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

管理jdk版本

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

完整pom.xml

<?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>

    <groupId>com.leyou.demo</groupId>
    <artifactId>springboot-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>

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

(2)、全域性屬性:application.properties /application.yml

mybatis:
  type-aliases-package: com.day01sboot.pojo
  mapper-locations: classpath:mappers/**/*.xml
  configuration:
    map-underscore-to-camel-case: true


spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis?useSSL=false
    username: root
    password: sswqzx

server:
  port: 8080

(3)、啟動類Application.java

@SpringBootApplication
@MapperScan("com.springcloud.mapper")//掃mapper包、不寫就要在mapper介面上寫
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

2、SpringBoot2.0整合SpringMvc

(1)、要在springboot中使用springmvc,只需要引入spring-boot-starter-web即可

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

(2)、自定義配置springMVC就修改application.yml

# 對映埠
server:
    port: 80

3、SpringBoot2.0整合Jdbc和事務

(1)、在pom.xml新增SpringBoot提供的jdbc啟動器

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

(2)、資料庫驅動

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

(3)、事務:哪裡要處理事務就在哪裡添加註解、@Transactional

  @Transactional
    public void deleteById(Long id){
        this.userMapper.deleteByPrimaryKey(id);
    }

(4)、連線池引數、application.yml

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis
    username: root
    password: root

4、SpringBoot2.0整合連線池

(1)、如果在pom.xml沒有引入連線池啟動器、SpringBoot自動幫我們引入了一個連線池 :HikariCP 、名日:光

所以、只要在application.yml指定連線池引數就行了

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis
    username: root
    password: root

(2)、如果要要用其他的連線池、就在pom.xml引入依賴(啟動器)

<!-- Druid連線池 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.6</version>
</dependency>

5、SpringBoot2.0整合mybatis

(1)啟動器:也就是pom.xml依賴

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

(2)、全域性屬性:配置resources/application.yml

mybatis:
  # mybatis 別名掃描
  type-aliases-package: com.leyou.pojo
  # mapper.xml檔案位置,如果沒有對映檔案,請註釋掉
  mapper-locations: classpath:mappers/**/*.xml

注、mapper介面要麼要介面上加@Mapper註解、要麼在啟動類上加掃包註解:@MapperScan("com.springboot01.mapper")

(3)、三層事例:(思路、寫全springboot三要點。啟動器:pom.xml、啟動類:app.java、全域性屬性:application.yml)

專案結構圖:

A、建立maven工程、引入依賴:啟動器

pom.xml依賴、springboot叫啟動器、父工程 、jdk版本、web啟動器必引

注:不用的啟動器不能亂引。會出bug

<?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>

    <groupId>com.day01springboot</groupId>
    <artifactId>day01boot</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>

    <!--jdk版本-->
    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <!--mybatis依賴/啟動器-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- mysql 依賴 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

    </dependencies>
</project>

B、編寫相關類,啟動類。。。(一個springboot只有一個啟動類)

App.java

package com.day01sboot;

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

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 0:11 2018/12/1
 */
@MapperScan("com.day01sboot.mapper")//掃包、不用在一個個在mapper介面上加
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }
}

web層:controller/QueryController.java

package com.day01sboot.controller;

import com.day01sboot.pojo.User;
import com.day01sboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 9:38 2018/12/1
 */
@RestController
@RequestMapping("user")
public class QueryController {

    @Autowired
    private UserService userService;

    @RequestMapping("query/{id}")
    public User queryById(@PathVariable("id")Long id){
        return  userService.queryById(id);
    }
}

Service層:service/UserService.java介面

package com.day01sboot.service;

import com.day01sboot.pojo.User;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 9:44 2018/12/1
 */
public interface UserService {
    User queryById(Long id);
}

Service層:service/UserServiceImpl.java實現類

package com.day01sboot.service.Impl;

import com.day01sboot.mapper.UserMapper;
import com.day01sboot.pojo.User;
import com.day01sboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 9:48 2018/12/1
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User queryById(Long id) {
       return userMapper.queryById(id);
    }
}

持久層:mapper/UserMapper.java介面

package com.day01sboot.mapper;

import com.day01sboot.pojo.User;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 0:55 2018/12/1
 */
public interface UserMapper {

    User queryById(Long id);
}

對映檔案、存放SQL語句:resources/mappers/UserMapper.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.day01sboot.mapper.UserMapper">

    <resultMap type="User" id="userMap" autoMapping="true">
        <id column="id" property="id"/>
    </resultMap>


    <sql id="commonSql">
      id,user_name,password,name,age,sex,birthday,created,updated
   </sql>

    <select id="queryById" resultMap="userMap">
        select <include refid="commonSql"></include> from tb_user where id = #{id}
    </select>

    <select id="findAllUsers" resultType="User">
        select <include refid="commonSql"></include> from tb_user
    </select>

    <insert id="insertUser" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
        INSERT INTO tb_user (
        user_name,
        password,
        name,
        age,
        sex,
        birthday,
        created,
        updated
        )
        VALUES
        (
        #{userName},
        #{password},
        #{name},
        #{age},
        #{sex},
        #{birthday},
        NOW(),
        NOW()
        )
    </insert>

    <update id="updateUser">
        UPDATE tb_user set
        user_name = #{userName},
        password = #{password},
        name = #{name},
        age = #{age},
        sex = #{sex},
        birthday = #{birthday},
        updated = NOW()
        WHERE
        id = #{id}
    </update>

    <delete id="deleteUser">
        delete from tb_user where
        id = #{id}
    </delete>

    <!--
             此處需要接收多個引數,有三種方式:
            方式一:#{0}   #{1}
            方式二:#{param1}  #{param2}
            方式三:在介面方法的形參中加@Param註解指定名字,這裡通過#{名字}來接收引數,如果只有
                   一個引數,#{名字}可以自定義

         -->
    <select id="login" resultType="User">
        select * from tb_user where user_name = #{userName} and password = #{password}
    </select>

</mapper>

實體類:pojo/User.java

package com.day01sboot.pojo;

import java.io.Serializable;
import java.util.Date;


public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;

    // 使用者名稱
    private String userName;

    // 密碼
    private String password;

    // 姓名
    private String name;

    // 年齡
    private Integer age;

    // 性別,1男性,2女性
    private Integer sex;

    // 出生日期
    private Date birthday;

    // 建立時間
    private Date created;

    // 更新時間
    private Date updated;

    public Long getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getUpdated() {
        return updated;
    }

    public void setUpdated(Date updated) {
        this.updated = updated;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", name=" + name
                + ", age=" + age + ", sex=" + sex + ", birthday=" + birthday + ", created=" + created
                + ", updated=" + updated + "]";
    }

}

 資料庫:

 

C、springboot配置檔案、application.yml

mybatis:
  type-aliases-package: com.day01sboot.pojo
  mapper-locations: classpath:mappers/**/*.xml
  configuration:
    map-underscore-to-camel-case: true


spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis?useSSL=false
    username: root
    password: sswqzx

server:
  port: 8080

《也學學大佬們、把原始碼傳到github

原始碼下載https://github.com/sswqzx/day01boot

6、通用mapper....

極其方便的使用mybatis單表的增刪改查

支援單表、但不支援通用的多表聯合查詢

通用mapper使用:

繼承通用的Mapper<T>,必須指定泛型<T>

泛型(實體類)<T>的型別必須符合的要求

1、表名預設使用類名,駝峰轉下劃線(只對大寫字母進行處理),如UserInfo預設對應的表名為user_info。

2、表名可以使用@Table(name = "tableName")進行指定,對不符合第一條預設規則的可以通過這種方式指定表名.

3、表字段預設為Java物件的Field名字駝峰轉下劃線形式.

4、可以使用@Column(name = "fieldName")指定不符合第3條規則的欄位名

5、使用@Transient註解可以忽略欄位,新增該註解的欄位不會作為表字段使用.

6、建議一定是有一個@Id註解作為主鍵的欄位,可以有多個@Id註解的欄位作為聯合主鍵.

例項:

啟動類:pom.xml

<?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">
    <parent>
        <artifactId>SpringCloud01</artifactId>
        <groupId>com.springclouds</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.springclouds</groupId>
    <artifactId>user-service</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
        </dependency>
    </dependencies>

</project>

啟動類:App.java

package com.springcloud;

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

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 11:52 2018/11/30
 */
@SpringBootApplication
@MapperScan("com.springcloud.mapper")
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }
}

相關類:

controller/UserController.java

package com.springcloud.controller;

import com.springcloud.pojo.User;
import com.springcloud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 11:14 2018/11/30
 */
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/{id}")
    public User queryById(@PathVariable("id")Long id){
        return userService.queryById(id);
    }
}

service/UserService.java

package com.springcloud.service;

import com.springcloud.mapper.UserMapper;
import com.springcloud.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 11:46 2018/11/30
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User queryById(Long id){
        return userMapper.selectByPrimaryKey(id);
    }
}

mapper/UserMapper

package com.springcloud.mapper;

import com.springcloud.pojo.User;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 11:47 2018/11/30
 */
public interface UserMapper extends tk.mybatis.mapper.common.Mapper<User> {
}

pojo/User.java

package com.springcloud.pojo;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 11:41 2018/11/30
 */
@Table(name = "tb_user")
public class User {
    private static final Long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    // 使用者名稱
    private String userName;

    // 密碼
    private String password;

    // 姓名
    private String name;

    // 年齡
    private Integer age;

    // 性別,1男性,2女性
    private Integer sex;

    // 出生日期
    private Date birthday;

    // 建立時間
    private Date created;

    // 更新時間
    private Date updated;

    public static Long getSerialVersionUID() {
        return serialVersionUID;
    }

    public Long getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getUpdated() {
        return updated;
    }

    public void setUpdated(Date updated) {
        this.updated = updated;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                ", birthday=" + birthday +
                ", created=" + created +
                ", updated=" + updated +
                '}';
    }
}

全域性屬性:resources/application.yml

server:
  port: 8081

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis
    username: root
    password: sswqzx

mybatis:
  type-aliases-package: com.springcloud.pojo

 

原始碼:https://github.com/sswqzx/SpringCloud01