修改配置文件4.0.0 org.springframework.boot spring-boot-starter-parent2.6.4 com.example demo0.0.1-SNAPSHOT demo Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-data-jdbcorg.springframework.boot spring-boot-starter-weborg.mybatis.spring.boot mybatis-spring-boot-starter2.2.2 mysql mysql-connector-javaruntime org.springframework.boot spring-boot-starter-testtest org.springframework.boot spring-boot-maven-plugin
在resource文件夹下创建application.yml配置文件(备注:其实SpringBoot底层会把application.yml文件解析为application.properties),本文创建了两个yml文件(application.yml和application-dev.yml),分别来看一下内容
application.ymlspring:
profiles:
active: dev
application-dev.yml
server:
port: 8080
spring:
datasource:
username: root
password: 1234
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
mybatis:
# 配置MyBatis的Mapper.xml文件所在位置:
mapper-locations: classpath:mapper
@Repository
public interface UserMapper {
User Sel(int id);
}
UserMapping.xml
UserService.javaselect * from user where id = #{id}
package com.example.demo.service;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public User Sel(int id){
return userMapper.Sel(id);
}
}
UserController.java
package com.example.demo.controller;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/testBoot")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("getUser/{id}")
public String GetUser(@PathVariable int id){
return userService.Sel(id).toString();
}
}
完成以上,下面在启动类里加上注解用于给出需要扫描的mapper文件路径
@MapperScan("com.example.demo.mapper")
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.example.demo.mapper")
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
最后启动,浏览器输入地址看看吧:http://localhost:8080/testBoot/getUser/1



