Pom,依赖如下,Spring Boot 版本为2.1.8.RELEASE
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
Application
@SpringBootApplication
@MapperScan("com.example.demo.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Controller
@RestController
@RequestMapping("/")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("user/{id}")
public String GetUser(@PathVariable int id) {
User user = userService.Sel(id);
if (null != user) {
return user.toString();
} else {
return "用户不存在";
}
}
}
Service
public interface UserService {
User Sel(int id);
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public String sayHello() {
return JsonBuilder.Info(JsonBuilder.SUCCESS_CODE,"Hello Spring!");
}
public User Sel(int id){
return userMapper.Sel(id);
}
}
Dao
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
User Sel(@Param("id") int id);
}
Entity
public class User {
private Integer id;
private String userName;
private String passWord;
private String realName;
//set,get
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", realName='" + realName + '\'' +
'}';
}
}
配置
server:
port: 8080
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
type-aliases-package: com.example.demo.entity
网友评论