Spring Boot Road Primer (14) --- Spring Boot integration with MyBatis

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Geffin/article/details/100051414

Digression

I believe we are coming from SSM era, a lot of time to see the profile of mind will collapse. Sometimes a configuration file in the wrong place, the entire project will probably not run, or simply can not find the error, "Mo angry" has become essential books program ape. . . Later Spring Boot turned appear, and finally do not have to face every day of the configuration file, inexplicably happy! Spring Boot frame is the best in the world! Haha.

Import dependence

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<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>
			<version>1.3.2</version>
		</dependency>
 
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
</dependencies>

Modify the configuration file

application.properties:

spring.profiles.active: dev

application-dev.properties:

server.port = 8080

spring.datasource.username = root
spring.datasource.password = root
spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
spring.datasource.driver-class-name = com.mysql.jdbc.Driver

mybatis.mapper-locations = classpath:mapping/*Mapper.xml
mybatis.type-aliases-package = edu.szu.test.entity

logging.level.com.example.mapper = debug

Here I use two configuration files, application.properties and application-dev.properties. Why can not we a configuration file written it?

This is because we need to configure multiple sets in a project environment, generally speaking, there are a variety of environmental projects, development environment, test environment, the production environment, and so on. Each parameter used in the environment is different, so we can put the configuration parameters for each environment to the master configuration file, which would like to use this in the environment when used only in the main configuration file configuration file to write on the line.

Note that, in the Spring Boot multi environment configuration file names need to meet application- {profile} .properties format, wherein {profile} identification corresponding to your environment, such as:

  1. application-dev.properties: Development Environment
  2. application-test.properties: Test Environment
  3. application-prod.properties: the production environment

As to which specific configuration file is loaded, it is necessary to set by spring.profiles.active application.properties file attribute, whose value corresponds to the value {profile}.

Create a data table

sql code is as follows:

CREATE TABLE `book` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(10) NOT NULL,
  `price` float NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Data table structure
Here Insert Picture Description
can see I've inserted two data

Creating pojo

Create an entity package, and then create a package inside the pojo

public class Book {

	private Integer id;
	private Float price;
	private String name;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Float getPrice() {
		return price;
	}
	public void setPrice(Float price) {
		this.price = price;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	@Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price='" + price + '\'' +
                '}';
    }
}

Create a mapper

Create a mapper package, and then create a mapper in the package inside

public interface BookMapper {
 
    Book selectById(int id);
}

Create a file mapper.xml

In the src / main / resources directory, create a folder mapping, and then create a new file BookMapper.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="edu.szu.test.mapper.BookMapper">
 
    <resultMap id="BaseResultMap" type="edu.szu.test.entity.Book">
        <result column="id" jdbcType="INTEGER" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="price" jdbcType="REAL" property="price" />
    </resultMap>
 
    <select id="selectById" resultType="edu.szu.test.entity.Book">
        select * from book where id = #{id}
    </select>
 
</mapper>

Create a service

Create a service package, and then create a service interface inside the package

public interface BookService {
	
	public Book select(int id);
}

Creating serviceImpl

ServiceImpl create a package, and then create a service implementation class in the package inside

@Service
public class BookServiceImpl implements BookService{

	@Autowired
	BookMapper bookMapper;
	
	public Book select(int id) {
		return bookMapper.selectById(id);
	}
}

Creating the Controller

Create a controller package, and then create a controller implementation class in the package inside

@RestController
@RequestMapping("/test")
public class BookController {

	@Autowired
    private BookService bookService;
 
    @RequestMapping("getBook/{id}")
    public String GetUser(@PathVariable int id){
        return bookService.select(id).toString();
    }
}

Modify the startup class

@SpringBootApplication
@MapperScan("edu.szu.test.mapper")
public class TestApplication {

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

}

Add a line comment @MapperScan ( "edu.szu.test.mapper") on the startup class, show mapper file path needs to be scanned.

Finally, we test it!

Enter in the browser http: // localhost: 8080 / test / getBook / 1, the following results
Here Insert Picture Description
enter the browser to http: // localhost: 8080 / test / getBook / 2, results are
Here Insert Picture Description
combined with the data table we created earlier
Here Insert Picture Description
proof Spring Boot and MyBatis has been successfully integrated.

Finally send my frame structure
Here Insert Picture Description

Reference: SpringBoot integration complete and detailed version Mybatis

Guess you like

Origin blog.csdn.net/Geffin/article/details/100051414