Springboot整合Thymeleaf和Mybatis
创建一个pojo类 tbcontent.java对应数据库中的字段
web层
输入localhost:8080/test/hello 开始运行代码
@Controller
public class hello {
@Autowired
private tbcont tbcont;
@RequestMapping("/test/hello")
<!--用来拦截地址栏输入的路径-->
public String hello(Model model){
List<tbcontent> tbcontents=tbcont.tbcontents();
model.addAttribute("ls",tbcontents);
return "hello";
}
}
service层
@Service
public class tbcont {
<!--把mapper中的TbContentMapper注入进来-->
@Autowired
private TbContentMapper contentMapper;
public List<tbcontent> tbcontents(){
List<tbcontent> y=contentMapper.select();
return y;
}
}
mapper文件
<!--有时会找不到mapper文件 加上这个注解 会直接找到这个文件-->
@Mapper
public interface TbContentMapper {
List<tbcontent> select();
}
mapper对应的xml文件
<?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">
<!--namespace 对应的mapper文件路径-->
<mapper namespace="com.example.demo.mapper.TbContentMapper">
<!--id 对应下面crud的resultMap属性 type 对应pojo与数据库字段对应的pojo类-->
<resultMap id="tbcontentmap" type="com.example.demo.pojo.tbcontent">
<!-- column 对应数据库中的字段 jdbctype对应数据库建表字段的类型 property 对应pojo类的属性 -->
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="parent_id" jdbcType="BIGINT" property="parent_id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="status" jdbcType="INTEGER" property="status"/>
</resultMap>
<select id="select" parameterType="com.example.demo.pojo.tbcontent" resultMap="tbcontentmap">
select id,name,parent_id,status from tb_content_category;
</select>
</mapper>
application.yml
#端口号 localhost:8080
server:
port: 8080
# 连接数据空
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/taotao?characterEncoding=utf8&useSSL=false&serverTimezone = GMT
username: root
password: root
#thmeleaf 用于验证 默认为true 测试的时候可以加上
thymeleaf:
cache: true
#mybatis 注入 指向mapper下的文件 和 pojo类
mybatis:
mapper-locations: classpath:/mappers/*.xml
type-aliases-package: com.example.demo.pojo
hello页面
<table>
//thymaleaf 循环语句
<tr th:each="s : ${ls}">
<td th:text="${s.name}"/>
<td th:text="${s.id}"/>
</tr>
</table>
<p th:text="${ls}"/>