一,创建项目
项目名称为 “springboot_mybatis_demo”,创建过程中勾选 “Web”,“MyBatis”,“MySQL”,第一次创建Maven需要下载依赖包(耐心等待)。
勾选 web,MyBatis,MySql三个选项。
二,实现
2.1 创建User类
package com.huwei.bean;
//创建一个User的bean
public class User {
private Long id;
private String userName;
private Integer age;
public User(){}
public User(Long id, String userName, Integer age) {
super();
this.id = id;
this.userName = userName;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", age=" + age + "]";
}
}
2.2创建UserMapper接口
创建接口UserMapper,并添加@Mapper注解
package com.huwei.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import com.huwei.bean.User;
// 创建一个User的mapper接口
@Mapper
public interface UserMaper {
// 查找User表中所有的数据
@Select("select * from user")
User queryAll();
}
2.3创建UserController
package com.huwei.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.huwei.bean.User;
import com.huwei.mapper.UserMaper;
@RestController
@RequestMapping("/web")
public class UserController {
@Autowired
private UserMaper userMaper;
@RequestMapping("/index")
public User queryAll(){
return userMaper.queryAll();
}
}
2.4设置application.properties文件
# mysql
spring.datasource.url=jdbc:mysql://localhost/spring_boot_demo?
useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=tq26556570
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
2.5创建数据库