SpringBoot--05.SpringBoot2.0学习小结

版权声明:转载请注明原始链接 https://blog.csdn.net/sswqzx/article/details/84668281

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

猜你喜欢

转载自blog.csdn.net/sswqzx/article/details/84668281