环境
- IDEA2017
- MyBatis 2.0.0
- druid 阿里数据库连接池
- MySQL5.5
在MySQL建立test数据库,建立user表,字段为id(int), name(varchar(20))
先上目录结构
1、 File -> new -> object -> Spring Initializer ->next
配置项目为maven项目
image.png image.png
image.png image.png
等待片刻,IDEA初始化项目 是网速而定
2、配置文件
在application.propertier文件中
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.typeAliasesPackage=com.tqh.demo.model
在model下创建User.java
注意User为pojo,创建时,要和数据库表结构一致
package com.myblog.model;
import java.io.Serializable;
public class User implements Serializable {
private int id;
private String name;
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
mapper/UserMapper.java
package com.myblog.mapper;
import com.myblog.model.User;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper {
@Select("select * from user where id = #{id}")
User selectUserById(int id);
}
service/UserService
package com.myblog.service;
import com.myblog.mapper.UserMapper;
import com.myblog.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public User selectUser(int id) {
return userMapper.selectUserById(id);
}
}
controller/UserController
package com.myblog.controller;
import com.myblog.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
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("show/{id}")
public String test(@PathVariable int id){
return userService.selectUser(id).toString();
}
}
浏览器中输入localhost://8080/show/1 看到下图内容,显示数据库中内容
网友评论