Springboot实验二(用配置文件的方式整合Mybatis)仅供参考!

(1)articleList.html 效果如下:
在这里插入图片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
<meta charset="UTF-8">
<title>article 列表</title>
</head>
<body>
<form method="get" th:action="@{'/articles/list'}">
<!--th:action 相当于 action-->
<input type="submit" value="查询">
</form>
<table cellspacing="1">
<thead>
<tr>
<th>id</th>
<th>标题</th>
<th>内容</th>
<th>操作</th>
</tr>
</thead>
<!--
Thymeleaf 遍历格式如下:
<tr th:each="user : ${userList}">
<td th:text="${user.name}">xxx</td>
</tr>
-->
<tbody th:each="article:${articleList}">
<tr>
<td th:text="${article.id}"></td>
<td th:text="${article.title}"></td>
<td th:text="${article.content}"></td>
<td>
<a th:href="@{/article/findById(id=${article.id})}">查看详情</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>

th:action属性: 用于设置查询表单的URL地址;
th:each属性: 指定了循环渲染的数据源和迭代变量;
th:text属性: 用于将变量的值渲染到HTML标签内部;
th:href属性: 指定了链接的URL地址,并使用${}语法将变量的值传递给后端接口。

(2**)articleDetail.html** 效果如下:

文章详情


评论列表:

  • 说:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
    <meta charset="UTF-8">
    <title>文章详情</title>
</head>
<body>
    <h2 th:text="${article.title}"></h2>
    <p th:text="${article.content}"></p>
    <hr>
    <h3>评论列表:</h3>
    <ul th:each="comment:${article.commentList}">
        <li>
            <span th:text="${comment.username}"></span> 说:
            <span th:text="${comment.content}"></span>
        </li>
    </ul>
</body>
</html>

(3)在 application.properties 配置 thymeleaf 页面信息:

spring.thymeleaf.cache=false
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

(4)pom.xml 中添加数据源依赖 —>druid-spring-boot-starter

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>

(5)创建实体类 ArticleComment,注意:此时实体类所在包为 domain。

public class Article {
    private int id;
    private String title;
    private String content;

    // getter and setter methods
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}
public class Comment {
    private int id;
    private String content;
    private String author;
    private int a_id;

    // getter and setter methods
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public int getA_id() {
        return a_id;
    }
    public void setA_id(int a_id) {
        this.a_id = a_id;
    }

    @Override
    public String toString() {
        return "Comment{" +
                "id=" + id +
                ", content='" + content + '\'' +
                ", author='" + author + '\'' +
                ", a_id=" + a_id +
                '}';
    }
}

(6)创建 Article 对应的 Mapper 接口 ArticleMapper,注意:此时接口类所在包为 mapper

@Repository
@Mapper
public interface ArticleMapper {
public Article findById(int id);
public List<Article> findAll();
}

(7)在 resources 路径下,创建 mapper 目录,并在其中创建 ArticleMapper.xml文件,实现 ArticleMapper 接口中对应的方法。

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tyut.mapper.ArticleMapper">

    <!-- 根据 id 查询一篇文章 -->
    <select id="findById" resultType="com.tyut.domain.Article" parameterType="int">
        SELECT id, title, content FROM t_article WHERE id = #{id}
    </select>

    <!-- 查询所有文章 -->
    <select id="findAll" resultMap="articleResultMap">
        SELECT id, title, content FROM t_article
    </select>

    <!-- 定义 Article 对象的 ResultMap -->
    <resultMap id="articleResultMap" type="com.tyut.domain.Article">
        <id column="id" property="id"/>
        <result column="title" property="title"/>
        <result column="content" property="content"/>
    </resultMap>

</mapper>

下面是对该 XML 文件中各个标签及其属性的解释:

  1. <mapper> 标签:定义 Mapper 文件,必须包含命名空间属性,指定该 Mapper 对应的 Java 包路径,如 namespace="com.tyut.mapper.ArticleMapper"

  2. <select> 标签:定义查询语句,可用于查询单个对象或多个对象,该标签必须指定 id 属性,指定该 SQL 语句的唯一标识符。

  • resultType 属性:指定该 SQL 语句的结果类型,如 resultType="com.tyut.domain.Article"

  • parameterType 属性:指定该 SQL 语句的参数类型,如 parameterType="int"

  • SQL 语句:SELECT 语句,用于查询数据表中的数据。

  1. <id> 标签:定义主键字段映射,用于表示该属性为数据库表的主键。
  • column 属性:指定该属性映射的数据库字段名称。

  • property 属性:指定该属性的 Java 对象属性名称。

  1. <result> 标签:定义普通字段映射,用于表示该属性为数据库表的普通列字段。
  • column 属性:指定该属性映射的数据库列名称。

  • property 属性:指定该属性的 Java 对象属性名称。

  1. <resultMap> 标签:定义映射关系,可用于定义复杂的字段映射,包括主键字段映射和普通字段映射。
  • id 属性:指定该 resultMap 的唯一标识符。

  • type 属性:指定该 resultMap 对应的 Java 类型。

  • <id> 子标签和 <result> 子标签:用于定义主键字段映射和普通字段映射,其中子标签属性同上述解释。

(8)在 application.properties 中配置数据库、数据源、mapper 映射等相关配置:(结合自身电脑情况修改)

spring.datasource.url=jdbc:mysql://localhost:3306/springboottest
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.druid.db-type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=20
spring.datasource.druid.min-idle=10
spring.datasource.druid.max-active=100
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.tyut.domain

(9)创建 ArticleController,用于进行请求接受和转发,注意:此时控制类所在包为 controller

@Controller
@RequestMapping("/articles")
public class ArticleController {

    @Autowired
    private ArticleMapper articleMapper;

    // 查询所有文章
    @GetMapping("/list")
    public String findAll(Model model) {
        List<Article> articleList= articleMapper.findAll();
        model.addAttribute("articleList", articleList);
        return "article/list"; // 返回视图模板 "article/list"
    }

    // 根据 id 查询单篇文章
    @GetMapping("/{id}")
    public String findById(@PathVariable int id, Model model) {
        Article article = articleMapper.findById(id);
        model.addAttribute("article", article);
        return "article/detail"; // 返回视图模板 "article/detail"
    }

}

(10)在 config 包下创建 MyConfig 类,重写 WebMvcConfigurer 自动配置类,实现 articleList 页面的路由注册。

@Configuration
public class MyConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/articles/list").setViewName("articleList");
    }
}

当用户在浏览器中访问"/articles/list"时,Spring MVC将会自动将请求路由到"articleList.html"这个视图模板上,完成页面的渲染和展示。这个视图模板对应的是控制器方法中返回的字符串。在这个例子中,控制器方法返回"articleList"字符串,即"articleList.html"视图模板的名称,Spring MVC自动将该字符串解析为对应的视图模板,将其展示在用户浏览器上。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在Spring Boot项目中整合MyBatis,可以按照以下步骤进行操作: 1. 在pom.xml文件中添加MyBatisMyBatis-Spring的依赖: ``` <dependencies> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- MyBatis-Spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> </dependencies> ``` 其中,`${mybatis.version}`和`${mybatis.spring.version}`是定义在项目中的版本号变量。 2. 在Spring Boot配置文件application.properties中配置MyBatis的相关属性: ``` # 数据库连接信息 spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.username=root spring.datasource.password=root # MyBatis配置信息 mybatis.type-aliases-package=com.example.demo.entity mybatis.mapper-locations=classpath:mapper/*.xml ``` 其中,`spring.datasource`是数据库连接信息,`mybatis.type-aliases-package`指定实体类的包名,`mybatis.mapper-locations`指定MyBatis Mapper文件的位置。 3. 创建MyBatis的Mapper接口和XML文件。 在Mapper接口中定义SQL语句,如: ``` public interface UserMapper { List<User> selectAllUsers(); } ``` 在XML文件中编写SQL语句,并与Mapper接口对应,如: ``` <?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="com.example.demo.mapper.UserMapper"> <select id="selectAllUsers" resultType="com.example.demo.entity.User"> SELECT * FROM users </select> </mapper> ``` 4. 在Spring Boot的Application类中添加`@MapperScan`注解,指定Mapper接口的扫描路径: ``` @SpringBootApplication @MapperScan("com.example.demo.mapper") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 其中,`@MapperScan`注解指定了Mapper接口的扫描路径,可以将其替换为对应的XML文件路径。 这样就完成了Spring Boot整合MyBatis的配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白夜的月亮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值