首先是创建项目:

ideal 创建spring项目的时候springboot版本选不了_springboot


选择Spring Initializr,保持如下选项,点击Next

ideal 创建spring项目的时候springboot版本选不了_mysql_02


自行修改,点击Next

ideal 创建spring项目的时候springboot版本选不了_spring_03


选择Web–>Spring Web,版本可自行选择,点击Next

ideal 创建spring项目的时候springboot版本选不了_mysql_04


自行修改项目名称,点击Finish

ideal 创建spring项目的时候springboot版本选不了_mysql_05


生成项目结构如下:

ideal 创建spring项目的时候springboot版本选不了_springboot_06


添加测试类:

package com.example.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author DH
 * @create 2019/11/12 - 16:56
 */
@RestController
public class HelloController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say() {
        return "hello";
    }
}

直接访问:

ideal 创建spring项目的时候springboot版本选不了_mysql_07


在application.yml添加如下设置可以修改端口及加路径前缀:(application.yml是直接修改配置文件application.properties后缀)

server:
  port: 8081
  servlet:
    context-path: /demo

再次访问:

ideal 创建spring项目的时候springboot版本选不了_spring_08


获取配置文件中的值:

server:
  port: 8081
  servlet:
    context-path: /demo

users:
  username: zhangsan
  password: 123
  nickname: 张三
  content: username:${users.username} password:${users.password}
package com.example.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author DH
 * @create 2019/11/12 - 16:56
 */
@RestController
public class HelloController {

    @Value("${users.username}")
    private String username;

    @Value("${users.password}")
    private String password;

    @Value("${users.nickname}")
    private String nickname;

    @Value("${users.content}")
    private String content;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say() {
//        return "hello";
        return "我的昵称是"+nickname+",账号是"+username+",密码是"+password+"---"+content;
    }
}

ideal 创建spring项目的时候springboot版本选不了_配置文件_09


在idea右下角将编码改为utf-8

ideal 创建spring项目的时候springboot版本选不了_spring_10


ideal 创建spring项目的时候springboot版本选不了_配置文件_11


也可以创建bean取值:

package com.example.demo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author DH
 * @create 2019/11/12 - 17:33
 */
@Component
@ConfigurationProperties(prefix = "student")
public class Student {

    private String id;
    private String name;
    private String sex;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

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

@Component:表明当前类是一个 Java Bean

@ConfigurationProperties(prefix = “student”):表示获取前缀为 sutdent 的配置信息

在使用@ConfigurationProperties时如有弹出

ideal 创建spring项目的时候springboot版本选不了_mysql_12


可取消该选项关闭提示

ideal 创建spring项目的时候springboot版本选不了_配置文件_13

student:
  id: 9527
  name: 小明
  sex: 男
@Autowired
private Student student;

@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String say() {
//        return "hello";
//        return "我的昵称是"+nickname+",账号是"+username+",密码是"+password+"---"+content;
    return student.getName();
}

ideal 创建spring项目的时候springboot版本选不了_springboot_14


可调用多个配置文件:(将配置文件复制两份,分别命名如下)

ideal 创建spring项目的时候springboot版本选不了_springboot_15


在application.yml中添加如下设置:dev表示使用application-dev.yml配置文件

spring:
  profiles:
    active: dev

多个url访问同一页面:

@RequestMapping(value = {"/hello","/hi"}, method = RequestMethod.GET)
public String say() {
//        return "hello";
//        return "我的昵称是"+nickname+",账号是"+username+",密码是"+password+"---"+content;
    return student.getName();
}

ideal 创建spring项目的时候springboot版本选不了_配置文件_16


ideal 创建spring项目的时候springboot版本选不了_springboot_17


获取url中的值:

@RequestMapping(value = "/look/{name}", method = RequestMethod.GET)
public String look(@PathVariable("name")String name) {
    return "我看见了" + name;
}

ideal 创建spring项目的时候springboot版本选不了_spring_18


也可以用问号传参的形式:

@RequestMapping(value = "/see", method = RequestMethod.GET)
public String see(@RequestParam("name")String name) {
    return "我看见了" + name;
}

ideal 创建spring项目的时候springboot版本选不了_spring_19


ideal 创建spring项目的时候springboot版本选不了_mysql_20


required表示参数是否必传,defaultValue代表默认值

@RequestMapping(value = "/see", method = RequestMethod.GET)
public String see(@RequestParam(value = "name", required = false, defaultValue = "xiaoming")String name) {
    return "我看见了" + name;
}

ideal 创建spring项目的时候springboot版本选不了_spring_21


用组合注解@GetMapping也是一样的

@GetMapping(value = "/see")
public String see(@RequestParam(value = "name", required = false, defaultValue = "xiaoming")String name) {
    return "我看见了" + name;
}

数据库操作:
添加依赖:

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

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

修改配置文件:

spring:
  profiles:
    active: dev
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:///springboot
    username: root
    password:
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

创建Teacher

package com.example.demo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * @author DH
 * @create 2019/11/12 - 18:12
 */
@Entity
public class Teacher {

    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    private String sex;

    public Teacher() {
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

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

重启项目

ideal 创建spring项目的时候springboot版本选不了_spring_22


修改配置文件:(刚才的问题是没有设置serverTimezone = GMT,为避免编码问题,将编码也设置上)

spring:
  profiles:
    active: dev
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:///springboot?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&serverTimezone = GMT
    username: root
    password:
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

生成了teacher表

ideal 创建spring项目的时候springboot版本选不了_springboot_23


添加接口

package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @author DH
 * @create 2019/11/12 - 18:27
 */
public interface TeacherRepository extends JpaRepository<Teacher, Integer> {
}

添加controller
新增:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author DH
 * @create 2019/11/12 - 18:29
 */
@RestController
public class TeacherController {

    @Autowired
    private TeacherRepository teacherRepository;
    
    @GetMapping("/add")
    public Teacher addTeacher() {
        Teacher teacher = new Teacher();
        teacher.setId(1);
        teacher.setName("张三");
        teacher.setSex("男");
        return teacherRepository.save(teacher);
    }
}

删除:

@GetMapping("/delete/{id}")
public void deleteTeacher(@PathVariable("id")Integer id) {
    teacherRepository.deleteById(id);
}

修改:(修改和新增调用同一个方法,如果数据不存在就是新增,存在就是修改)

@GetMapping("/update/{id}")
public Teacher updateTeacher(@PathVariable("id")Integer id,
                             @RequestParam(value = "name", required = false)String name,
                             @RequestParam(value = "sex", required = false)String sex) {
    Teacher teacher = new Teacher();
    teacher.setId(id);
    teacher.setName(name);
    teacher.setSex(sex);
    return teacherRepository.save(teacher);
}

查询:
查所有:

@GetMapping("/findAll")
public List<Teacher> findAll() {
    return teacherRepository.findAll();
}

通过id查:

@GetMapping("/find/{id}")
public Optional<Teacher> findInfo(@PathVariable("id")Integer id) {
     return teacherRepository.findById(id);
}

通过其他字段查:(修改dao层接口)

package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @author DH
 * @create 2019/11/12 - 18:27
 */
public interface TeacherRepository extends JpaRepository<Teacher, Integer> {

    Teacher findByName(String name);
}

修改controller:

@GetMapping("/findByName")
public Teacher findByName(@RequestParam("name")String name) {
    return teacherRepository.findByName(name);
}

事务的使用:@Transactional

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author DH
 * @create 2019/11/13 - 10:03
 */
@Service
public class TeacherService {

    @Autowired
    private TeacherRepository teacherRepository;

    @Transactional
    public void saveTwo() {
        Teacher teacher1 = new Teacher();
        teacher1.setName("aa");
        teacher1.setSex("nan");
        teacherRepository.save(teacher1);
        System.out.println(2/0);
        Teacher teacher2 = new Teacher();
        teacher2.setName("bb");
        teacher2.setSex("nv");
        teacherRepository.save(teacher2);
    }
}
@GetMapping("/saveTwo")
public void saveTwo() {
    teacherService.saveTwo();
}

如果不使用@Transactional注解,那么中间出现异常的时候第一条数据会添加到数据库,第二条数据则不会添加,这显然不是我们想要的
注:如果加入注解无效,在对应的数据库表执行下述脚本修改储存引擎

ALTER TABLE boy ENGINE=innodb