说明
快速创建出springboot项目,并且创建一个user对象进行测试
idea加载依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.4</version>
</dependency>
创建文件夹
在java文件夹下创建基本的Controller,dao,pojo,service文件夹,注意跟主程序是同一目录
在resource文件夹下创建mybatis文件夹以及application.yaml文件
补充文件
applicatiion.yaml写如下内容,注意更改数据库mytest名称
server:
port: 8080
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
username: root
password: 123
url: jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
type-aliases-package: com.qilu.pojo
mapper-locations: classpath:/mybatis/*.xml
logging:
file:
name: log/log.log
level:
root: info
com.qilu: debug
创建一个UserDao在dao文件夹下
@Repository
@Mapper
public interface UserDao {
public List<User> findALl();
public User findUserById(Integer id);
}
在mybatis文件夹下面创建UserMapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.laixi.dao.UserDao">
<select id="findALl" resultType="com.laixi.pojo.User">
select * from user;
</select>
<select id="findUserById" parameterType="int" resultType="com.laixi.pojo.User">
select * from user where id = #{id}
</select>
</mapper>
创建pojo类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private String pwd;
private String perm;
}
创建一个UserController类
@Controller
public class UserController {
@Autowired
UserService userService;
@GetMapping("/success")
public String test(Model model){
model.addAttribute("msg",userService.findUserById(1));
return "success";
}
}
在Service下面创建UserService接口和UserServieImpl实现类
public interface UserService {
public List<User> findALl();
public User findUserById(Integer id);
}
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserDao userDao;
@Override
public List<User> findALl() {
return userDao.findALl();
}
@Override
public User findUserById(Integer id) {
return userDao.findUserById(id);
}
}
在controller下面创建一个usercontroller
@Controller
public class UserController {
@Autowired
UserService userService;
@GetMapping("/test1")
@ResponseBody
public String test1(){
return userService.findALl().toString();
}
@GetMapping("/hello")
@ResponseBody
public String hello(){
return "success";
}
@GetMapping("/success")
public String test2(Model model){
model.addAttribute("msg",userService.findUserById(1));
return "success";
}
}
在templates文件夹下面创建一个success的测试文件
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>success</title>
</head>
<body>
[[${msg}]]
</body>
</html>