1. Use idea to create a Spring Boot project

  1. From the file-new-Project menu of idea, select Spring Initializr

  1. Fill in the project name, all other default

  1. Select the package you want to import, for the moment, the package you want to import for the Web. Subsequently, it will be added in POM.xml according to its actual situation.

  1. Path to the disk where the project is saved


2. Application. Yml file

server:
  port: 8082 # port
  servlet:
    context-path: /girl # the project name

Copy the code

2.1 Use the @value annotation to import configuration file parameters

Yml configuration file

server:
      port: 8082 # port
      servlet:
        context-path: /girl # the project name
cupSize: B

Copy the code

The Controller code

@RestController
public class HelloController {

    @Value("${cupSize}")
    private String cupSize;

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String say(a){
        return "cupSize:"+cupSize; }}Copy the code

Page output


2.2 Self-Referencing Parameters in the Configuration File

Yml configuration file

server:
      port: 8082 # port
      servlet:
        context-path: /girl # the project name
cupSize: B
age: 18
content : "cupSize: ${cupSize},age: ${age}"
Copy the code

Controller call code

@RestController
public class HelloController {
    

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

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String say(a){
        returncontent; }}Copy the code

Write to a class via @configurationProperties

Yml file

server:
      port: 8082 # port
      servlet:
        context-path: /girl # the project name
girl:
  cupSize: B
  age: 18

Copy the code

Referenced bean class

  1. Using @ConfigurationProperties requires importing packages
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
Copy the code
  1. Annotate the bean with @ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {

    private String cupSize;

    private Integer age;
Copy the code

The controller injects the calling code

@RestController
public class HelloController {

    @Autowired
    private GirlProperties girlProperties;

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String say(a){
        returngirlProperties.getCupSize(); }}Copy the code

Use spring.profiles. Active to switch between using configuration files for development and production environments

spring:
  profiles:
    active: prod

Copy the code


3. Use of Controller

3.1 @requestMapping Multiple urls point to the same method

To map two or more urls to the same method, you can use collections.

@RestController
public class HelloController {

    @Autowired
    private GirlProperties girlProperties;

    @RequestMapping(value = {"/hello"."/hi"},method = RequestMethod.GET)
    public String say(a){
        returngirlProperties.getCupSize(); }}Copy the code

3.2 @requestMapping points to a class

Request the address is: http://localhost:8082/girl/hello/say

@RestController
@RequestMapping("/hello")
public class HelloController {

    @Autowired
    private GirlProperties girlProperties;

    @RequestMapping(value = "/say",method = RequestMethod.POST)
    public String say(a){
        returngirlProperties.getCupSize(); }}Copy the code

3.3 Use of @PathVariable

Gets the value defined on the request address

  @RequestMapping(value = "/say/{id}",method = RequestMethod.GET)
    public String say(@PathVariable("id") Integer id ){
        return "id:" +id;
    }

Copy the code

Request address: http://localhost:8082/girl/hello/say/100

Output effect:


3.4 use of @requestParam

Get the requested address on? Key =value Parameter value

   @RequestMapping(value = "/say",method = RequestMethod.GET)
    public String say(@RequestParam("id") Integer myId ){
        return "id:" +myId;
    }

Copy the code

Request address: http://localhost:8082/girl/hello/say? id=666

Output effect:

  • The rest of the parameters

    Value is the default parameter

    Required indicates whether the parameter is required

    DefaultValue specifies the defaultValue

       @RequestMapping(value = "/say",method = RequestMethod.GET)
        public String say(@RequestParam(value = "id", required = false,defaultValue = "0") Integer myId ){
            return "id:" +myId;
        }
    
    
    Copy the code

4. Compose annotations

  • @GetMapping
  • @PostMapping
  • @DeleteMapping
  • @PutMapping

@requestMapping (value = “/say”,method = requestmethod.get) @requestMapping (value = “/say”,method = requestmethod.get)

  @GetMapping("/say")
    public String say(@RequestParam("id") Integer myId ){
        return "id:" +myId;
    }

Copy the code

4.Spring Boot Connects to the database

4.1 configuration

Pom.xml introduces JPA and mysql driver packages

  • Note: if you use mysql5.x, remember to select 5.1x version of the database driver package, otherwise an error will occur
 <! -- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <! -- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>


Copy the code

Application. yml Configuration content

  • The ddl-auto parameter indicates that the project starts the construction of database tables and entities. Typically, create, update, and None are used
    • Create indicates that the table is re-deleted at each startup
    • Update a table to which no corresponding entity column exists, and add additional columns to the table
    • None does nothing
spring:
  profiles:
    active: dev
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: JDBC: mysql: / / 127.0.0.1:3306 / dbgirl
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    The default engine is MyISAM, which does not support transaction rollback
    # add the following Settings for JPA to create tables with InnoDB engine that supports transactions,
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect


Copy the code

Entity class

  • Use the @entity annotation above the class to indicate an Entity table mapping
  • @id represents the primary key
  • @generatedValue stands for self-growth
  • Don’t forget that you must have a constructor with no arguments
@Entity
public class Girl {

    @Id
    @GeneratedValue
    private Integer id;

    private String cupSize;

    private Integer age;

    private Integer height;

    public Girl(a) {}

Copy the code

4.2 JPA findAll()

Write an interface class that inherits the JpaRepository interface

  • JpaRepository

    The first argument: entity class, the second argument: primary key type
    ,integer>
public interface GirlRepository extends JpaRepository<Girl.Integer> {}Copy the code

The controller calls

  • FindAll () queries all
@RestController
public class GirlController {

    @Autowired
    private GirlRepository girlRepository ;

    /** * query all girls *@return* /
    @GetMapping("/girls")
    public List<Girl> girlList(a){
        returngirlRepository.findAll(); }}Copy the code

Output effect:


4.3 JPA add object [save()]

The controller calls

Post adds a piece of data and returns the added object

    /** * add a girl *@param cupSize
     * @param age
     * @param height
     * @return* /
    @PostMapping("/girls")
    public Girl girlAdd(@RequestParam("cupSize") String cupSize,
                        @RequestParam("age") Integer age,
                        @RequestParam("height") Integer height){
        Girl girl = new Girl();
        girl.setCupSize(cupSize);
        girl.setAge(age);
        girl.setHeight(height);
        return girlRepository.save(girl);
    }

Copy the code

Output effect:


4.4 JPA Query findById(id).orelse (null) by ID

FindById (id).orelse (null) findById(id).orelse (null)

  // Query a girl
    @GetMapping("/girls/{id}")
    public Girl girlFindOne(@PathVariable("id") Integer id){
        return girlRepository.findById(id).orElse(null);
    }

Copy the code

4.5 JPA update object [save()]

    // Update a girl
    @PutMapping("/girls/{id}")
    public Girl girlUpdate(@PathVariable("id") Integer id,
                           @RequestParam("cupSize") String cupSize,
                           @RequestParam("age") Integer age,
                           @RequestParam("height") Integer height){
        Girl girl = new Girl();
        girl.setId(id);
        girl.setCupSize(cupSize);
        girl.setAge(age);
        girl.setHeight(height);
        return girlRepository.save(girl);
    }

Copy the code

Postman uses the put method to pass parameters using X-www-form-urlencoded


4.6 JPA deleteById(id)

The controller calls

// Delete a girl
    @DeleteMapping("/girls/{id}")
    public void girlDel(@PathVariable("id") Integer id){
        girlRepository.deleteById(id);
    }

Copy the code

4.7 JPA Searches by Other Field Conditions

GirlRepository extended query interface

  • You need to follow the specification, the findBy field
public interface GirlRepository extends JpaRepository<Girl.Integer> {

    public List<Girl> findByAge(Integer age);

}

Copy the code

The controller calls

    // Check girls by age
    @GetMapping("/girls/age/{age}")
    public List<Girl> girlListByAge(@PathVariable("age") Integer age){
        return girlRepository.findByAge(age);
    }

Copy the code

4.8 Transaction Management

Putting @service and @Component on top of classes both support transaction rollback

  • Note [otherwise rollback cannot be done]

    The @transactional callback method must be public

    Mysql database engine must be InnoDB, especially check whether the corresponding table is InnoDB

Spring Boot 2.0 JPA automatically generates tables with MyISAM as the default engine, and does not support transaction rollback. org.hibernate.dialect.MySQL5InnoDBDialect

spring:
  profiles:
    active: dev
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: JDBC: mysql: / / 127.0.0.1:3306 / dbgirl
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    The default engine is MyISAM, which does not support transaction rollback
    # add the following Settings for JPA to create tables with InnoDB engine that supports transactions,
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect


Copy the code
  • example

The Service class code

@Service
public class GirlService {

    @Autowired
    private  GirlRepository girlRepository;

    @Transactional
    public void insertTwo(a){
        Girl girlA = new Girl();
        girlA.setCupSize("A");
        girlA.setAge(18);
        girlA.setHeight(155);
        girlRepository.save(girlA);

        Girl girlB = new Girl();
        girlB.setCupSize("BBBBB");
        girlB.setAge(16);
        girlB.setHeight(170); girlRepository.save(girlB); }}Copy the code