SpringBoot Road (–)

Has been using Springboot to do projects, but like a duck to a shelf, there is no system from scratch to a project to create an application, recently decided to do a Springboot out-of-the-box project, mainly feel very vegetables, for Springboot only stay at the stage of use, So I want to do one from scratch to strengthen my understanding. In the later stage, I plan to use Vue and SpringBoot project to make a project with separate front and back ends. I plan to use iView Ui. I’m used to using Element and want to change the style.

Create a SpringBoot application

This chapter will introduce two ways to create a SpringBoot project, according to the Sping BOot official documentation recommended, after filling in the information can download a Zip file, and then decompress, import in IDEA

The second direct use of IDEA is recommended
Sping InitializrTo create, as shown below


Select the tool to use, in this case first
Web,
MySQL,
Mybatis“And then the next step is ok. (If there is no connection to the database, you need to comment out MySQL in POM.xml. Otherwise, you will get an error when you start the database.)


This is the directory structure

Open the
DemoApplicationThis is a
SpingBootThe startup class, where
@SpringBootApplicationIs a configuration class annotation that does something like
@Configuration.
@EnableAutoConfiguration.
@ComponentScanThe combination of these notes,
@ConfigurationThe function is to allow registration of additional
beans.
@ComponentScanIs used to start component scanning,
@EnableAutoConfigurationThe purpose is to start
Sping BootAutomatic configuration of.


And then we’ll create a new one
Controlleradd
@RestControllerAnnotations,
@RestControllerAnnotations are very convenient in our development, because the best we have so far is that the back end returns JSON data and gives it to the front end to parse, which is very convenient when you use it


And then we use
PostManTo test the boot up,
headerSelect the {key: the content-type, value: application/json},
bodySelect the
rawMode, and then send the request, and you can see hello world comes back to us.

Integrate Mybatis to connect database

SpingBoot is also very easy to integrate Mybatis by adding it to poM files

<dependency>

      <groupId>org.mybatis.spring.boot</groupId>

      <artifactId>mybatis-spring-boot-starter</artifactId>

      <version>1.3.2</version>

</dependency>

Copy the code

Integration of the Mysql:

<dependency>

      <groupId>mysql</groupId>

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

      <scope>runtime</scope>

</dependency>

Copy the code

Then we go to application.properties to configure the drivers that connect to the database

# connect MySQL

Spring. The datasource. Url = JDBC: mysql: / / 127.0.0.1:3306 / demo? useSSL=false&useUnicode=true&characterEncoding=utf-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&allowPublicKeyRetrieval=true

spring.datasource.username=root

spring.datasource.password=123456

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

Copy the code

Then create a new mybatis configuration class: MybatisConfigurer

@Configuration

public class MybatisConfigurer {



    @Bean

    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {

        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();

        factory.setDataSource(dataSource);

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        factory.setMapperLocations(resolver.getResources("classpath:/Mapper/**/*Mapper.xml"));

        return factory.getObject();

    }



    @Bean

    public MapperScannerConfigurer mapperScannerConfigurer(a) {

        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();

        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");

        mapperScannerConfigurer.setBasePackage("com.ywbjja.demo");

        return mapperScannerConfigurer;

    }



}

Copy the code

The mapper. XML file is configured in the configuration file. Spring Boot will look for the mapper. XML file in the directory according to the configured address. Create a User table in the database

CREATE TABLE `demo`.`user` (

  `user_id` BIGINT NOT NULL.

  `user_name` VARCHAR(45NOT NULL.

  PRIMARY KEY (`user_id`))

ENGINE = InnoDB

DEFAULT CHARACTER SET = utf8

COMMENT = 'User table';

Copy the code

Then add a data test:

And then the Mapper interface Serviece class, which I won’t write here, the Controller class code is like this,

@RestController

public class UserController {



    @Autowired

    private UserService userService;



    @RequestMapping(value = "/user/getUser")

    public User getUser(@RequestBody Map<String ,Object> map){

        return userService.queryUserById(map);

    }

}

Copy the code

The recommendation here is to use Map as the parameter, which saves a lot of code, and then use postman to test the results.

0 configuration integration Mybatis

Is creating a New MybatisConfigurer a hassle? Add @mapperscan annotation to the Sping Boot Boot class. This annotation will scan the Mapper interface in this directory

@SpringBootApplication

@MapperScan(value = "com.ywbjja.demo")

public class DemoApplication {



    public static void main(String[] args) {

        SpringApplication.run(DemoApplication.class, args);

    }



}

Copy the code

Then configure the mapper. XML file address in the configuration file

mybatis.mapper-locations=classpath*:Mapper/**/*Mapper.xml

Copy the code

This can also be successful, eliminating the configuration class, very convenient. Good to this end, if there is a wrong place welcome to spray me!! Spray me loudly!! Thank you very much… The next section intends to talk about SpringBoot’s uniform return of objects and exception handling