file-new-project,新建一个spring initializr,在选择dependencies页面,web选项卡选择web,template engines页面选择thymeleaf,SQL选项卡选择 MySql、JDBC、MyBatis
创建好的结构目录
在springboot的配置文件中配置数据库连接(我习惯使用yml文件)
spring:
datasource:
url: jdbc:mysql://localhost:3306/user
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
在templates文件夹下新建一个index.html,同时新建好mybatis对应的目录文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<span th:text="${user.name}"></span>
</html>
@Controller
public class IndexController {
@Autowired
private UserService userService;
@RequestMapping("/")
public String index(Model model){
User user = userService.findUserByUserid(1);
model.addAttribute("user",user);
return "index";
}
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findUserByUserid(Integer id) {
User userByUserid = userMapper.findUserByUserid(id);
return userByUserid;
}
}
public interface UserMapper {
@Select("select * from user where id = #{userId}")
User findUserByUserid(@Param("userId") Integer userId);
}
最后在springboot的启动类上添加mapper文件的扫描
@SpringBootApplication
@MapperScan("cn.test.mapper")
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
启动项目,访问http://127.0.0.1:8080/,即可
![](https://i-blog.csdnimg.cn/blog_migrate/3ff356609a76b0b3ad396c76385aa29e.png)