天天看點

Springboot整合Mybatis詳細步驟

spring boot整合mybatis

1、添加依賴

<!-- 整合mysql 與mybatis  開始 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.2</version>
		</dependency>
<!-- 整合mysql 與mybatis 結束-->
           

2、application.yml中添加配置

Springboot整合Mybatis詳細步驟

3、添加mybatis-config.xml檔案

路徑:

Springboot整合Mybatis詳細步驟

内容:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
</configuration>
           

4、建立mapper包及xml檔案

Springboot整合Mybatis詳細步驟

UserMapper.java :

public interface UserMapper {
    List<User> getAllUser();
}
           

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.mythical.rosefinch.business.mapper.UserMapper">
    <select id="getAllUser" resultType="com.mythical.rosefinch.entity.bean.User">
        select * from t_user;
    </select>
</mapper>
           

5、啟動類掃描mapper包 @MapperScan

@SpringBootApplication
@MapperScan("com.mythical.rosefinch.business.mapper")
public class RosefinchBusinessApplication {

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

}
           

6、開始測試

service層代碼:

@Service
@Transactional
public class UserService {
	@Autowired
	private UserMapper userMapper;
	
	public List<User> getAllUser(){
		return userMapper.getAllUser();
	}
}
           

controller層代碼:

@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	@RequestMapping("/getAllUser")
    public List<User> getAllUser() {
        return userService.getAllUser();
    }
}
           

頁面通路:

http://127.0.0.1:8081/user/getAllUser

結果:

Springboot整合Mybatis詳細步驟