springboot整合Thymeleaf与mybatis

一、多环境配置文件

1.1、加载位置

  1. file: ./config/application

  2. file: ./application

  3. classPath: /config/application

  4. classPath: /application (系统默认)

     优先级1:项目路径下的config文件夹配置文件
     优先级2:项目路径下配置文件
     优先级3:资源路径下的config文件夹配置文件
     优先级4:资源路径下配置文件

1.2、property的多文档块

通过spring.profiles进行命名,然后通过spring.profiles.action经行选择!

#比如在配置文件中指定使用dev环境,我们可以通过设置不同的端口号进行测试;
#我们启动SpringBoot,就可以看到已经切换到dev下的配置了;
spring.profiles.active=dev

1.3、yml的多文档块

​ 和properties配置文件中一样,但是使用yaml去实现不需要创建多个配置文件,更加方便了 ! 通过“—”进行分隔!

server:
  port: 8081
#选择要激活那个环境块
spring:
  profiles:
    active: prod
    
---
server:
  port: 8083
  spring:
    profiles: dev	#配置环境的名称
    
---
server:
  port: 8084
  spring:
    profiles: prod	#配置环境的名称

1.4、静态资源导入优先级

  1. 在springboot,我们可以使用以下方式处理静态资源
    • webjars localhost:8080/webjars/
    • public, static, /**, resources localhost:8080/
  2. 优先级: resources > static (默认) > public

二、Thymeleaf

2.1、导入依赖

<!--thymeleaf-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.2、结论

只需要使用thymeleaf,只需要导入对应的依赖,将html放在templates目录下即可!

// 前缀
public static final String DEFAULT_PREFIX = "classpath:/templates/";
// 后缀
public static final String DEFAULT_SUFFIX = ".html";

导入约束,命名空间

<html lang="en" xmlns:th="http://www.thymeleaf.org">

2.3、符号

  • 变量:${…}

  • 选择:*{…}

  • 消息:#{…}

  • url:@{…}

  • 提取公共部分:~{…}

2.4、提取公共部分

2.4.1、顶部导航栏

提取公共部分:

导入:

<!--顶部导航栏-->
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar">
    <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Company name</a>
    <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
    <ul class="navbar-nav px-3">
        <li class="nav-item text-nowrap">
            <a class="nav-link" th:href="@{/index}">Sign out</a>
        </li>
    </ul>
</nav>
2.4.2、侧边栏
<!--侧边栏-->
<nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="topbar">
    <div class="sidebar-sticky">
        <ul class="nav flex-column">          
            <li class="nav-item">
                <a class="nav-link active" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home">
                        <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
                        <polyline points="9 22 9 12 15 12 15 22"></polyline>
                    </svg>
                    11
                    <span class="sr-only">(current)</span>
                </a>
            </li>            
        </ul>
    </div>
</nav>

2.5、测试

  1. 编写一个Controller
@Controller
public class IndexController {
    @RequestMapping("/test")
    public String test(Model model) {
        model.addAttribute("msg","springboot");
        return "test";
    }
}
  1. 编写一个测试页面 test.html 放在 templates 目录下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
<div th:text="${msg}"></div>
</body>
</html>

三、MyBatis

3.1、application.yml

mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml # mapper映射文件位置
  type-aliases-package: nuc.edu.entity # 实体类所在的位置
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #用于控制台打印sql语句
    aggressive-lazy-loading: false
    lazy-loading-enabled: true
    map-underscore-to-camel-case: true
server:
  port: 8080
  servlet:
    application-display-name: aaa
    context-path: /aaa
spring:
  thymeleaf:
    cache: false
    suffix: .html
    encoding: utf-8
    prefix: classpath:/templates/
  resources:
    static-locations: classpath:/templates/,classpath:/static/

3.2、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">
<mapper namespace="org.mybatis.example.BlogMapper">
    <select id="selectBlog" resultType="Blog">
    	select * from Blog where id = #{id}
  	</select>
</mapper>

3.3、复杂查询

3.3.1、一对多

一名老师对应多名学生。

实体类:

public class Teacher {
    private int id;
    private String name;
    private List<Student> students;
}

public class Student {
    private int id;
    private String name;
    private int tid;
    //private Teacher teacher;
}

mapper:

public interface TeacherMapper {
    Teacher findTeaById(@Param("tid") int id);
}

按照结果集映射查询:

<resultMap id="teacher_student" type="Teacher">
    <id property="id" column="tid"/>
    <result property="name" column="tname"/>
    <collection property="students" ofType="Student">
        <id property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>

<select id="findTeaById" resultMap="teacher_student">
    select t.id tid, t.name tname, s.id sid, s.name sname
    from teacher t, student s
    where s.tid = t.id and t.id = #{tid}
</select>
3.3.2、一对一

实体类:

public class Student {
    private int id;
    private String name;
    //private int tid;
    private Teacher teacher;
}

public class Teacher {
    private int id;
    private String name;
    //private List<Student> students;
}

mapper:

public interface StudentMapper {
    List<Student> findAllStu();
}

按照结果集映射查询

<resultMap id="student_teacher" type="student">
    <id property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="Teacher">
        <result property="name" column="tname"/>
    </association>
</resultMap>

<select id="findAllStu" resultMap="student_teacher">
    select s.id sid, s.name sname, t.name tname
    from student s, teacher t
    where s.tid = t.id
</select>
3.3.3、总结

1、关联 - association 【一对一】

2、集合 - collection 【一对多】

3、javaType & ofType

  • javaType :用来指定实体类中的属性类型。
  • ofType :用来指定映射到List或者集合中的pojo类型,泛型中的约束类型。(当一对多时,类型为集合,取集合对应的泛型)

3.4、maven配置资源过滤问题

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
    </resource>
</resources>

3.5、驼峰命名开启

mybatis 驼峰命名

在这里插入图片描述

四、Druid

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/springboot2?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    # mysql 5版本不需要加cj,8版本需要加cj,但向下兼容,5版本也可以加cj
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    
    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    # 初始化大小,最小,最大
    initialSize: 5
    minIdle: 5
    maxActive: 20
    # 配置获取连接等待超时的时间
    maxWait: 60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    timeBetweenEvictionRunsMillis: 60000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    # stat:监控统计、log4j:日志记录、wall:防御sql注入
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j   
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以参考以下步骤来实现Spring Boot整合Thymeleaf的增删改查示例: 1. 首先,使用Spring Initializr进行项目初始化。你可以参考\[1\]中提供的博客文章来了解如何新建一个Spring Boot项目,并在勾选依赖时选择与MyBatis相关的依赖。 2. 导入必要的依赖。在你的项目的pom.xml文件中,添加以下依赖: ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.5</version> </dependency> ``` 这些依赖将帮助你实现Spring BootMyBatisThymeleaf和分页插件的整合。\[3\]提供了一个示例的依赖配置。 3. 创建实体类和Mapper接口。根据你的需求,创建相应的实体类和Mapper接口,用于定义数据库表和操作。 4. 编写Mapper.xml文件。在resources目录下创建一个与Mapper接口对应的Mapper.xml文件,编写SQL语句来实现增删改查操作。 5. 创建Service层和Controller层。在你的项目中创建Service层和Controller层,用于处理业务逻辑和接收请求。 6. 编写Thymeleaf模板。在resources/templates目录下创建相应的Thymeleaf模板文件,用于展示数据和接收用户输入。 通过以上步骤,你就可以实现Spring Boot整合Thymeleaf的增删改查示例了。你可以参考\[2\]提供的博客文章来了解如何进一步完善你的项目,实现多表查询、模糊查询和分页展示等功能。 #### 引用[.reference_title] - *1* *2* [springboot整合mybatis实现简单的单表增删改查(完整代码可下载)](https://blog.csdn.net/qq_51580852/article/details/127327287)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [SpringBoot+Mybatis+thymeleaf实现增删改查](https://blog.csdn.net/weixin_63920305/article/details/127975650)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值