要导入以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
配置数据库账号、密码等,以及mapper.xml的位置:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=276689237abc
spring.datasource.url=jdbc:mysql://localhost:3306/biyesheji
mybatis.mapper-locations=classpath:mapper/*.xml
controller:
/**
* @author myllxy
* @create 2020-04-26 11:01
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
IUserService userService;
@ResponseBody
@RequestMapping(value = "/getAll",method = RequestMethod.POST)
public List<User> getAll() {
return userService.getAll();
}
}
service:
注意IUserService 要被主启动类扫描到,IUserServiceImpl要打上@Service注解
/**
* @author myllxy
* @create 2020-04-26 11:07
*/
public interface IUserService {
List<User> getAll();
}
@Service
public class IUserServiceImpl implements IUserService {
@Autowired
private UserDao userDao;
@Override
public List<User> getAll() {
return userDao.getAll();
}
}
domain:
/**
* @author myllxy
* @create 2020-04-26 10:56
*/
@Data
public class User {
@NotNull(message = "userId不能为空")
private Integer userId;
@NotNull(message = "email不能为空")
private String email;
@NotNull(message = "userName不能为空")
private String userName;
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", email='" + email + '\'' +
", userName='" + userName + '\'' +
'}';
}
}
dao与xml:
public interface UserDao {
/**
* 获取所有学生数据
*
* @return
*/
List<User> getAll();
}
<?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="cn.myllxy.testmybatis2.dao.UserDao">
<resultMap id="userResultMap" type="cn.myllxy.testmybatis2.domain.User">
<id column="userId" property="userId"/>
<result column="userName" property="userName"/>
<result column="email" property="email"/>
</resultMap>
<select id="getAll" resultMap="userResultMap">
select userId,email,userName from user
</select>
</mapper>