Springboot整合Thymeleaf和Mybatis

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}"/>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值