springboot整合mybatis及thymeleaf

springboot整合mybatis及thymeleaf


前言

该文章是自己在整合springboot,mybatis,thymeleaf的心得


一、demo结构

二、文件内容

1.pom文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
		<thymeleaf-spring5.version>3.0.9.RELEASE</thymeleaf-spring5.version>
		<!--  <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>     -->   
		<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
	</properties>

	<dependencies>
		<dependency> 
		     <groupId>org.springframework.boot</groupId> 
		     <artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.3</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
        <!--devtools热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>
	</dependencies>

	<build>
		<resource>
		 <directory>src/main/resources</directory>
		</resource>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<configuration>
                <fork>true</fork>
            </configuration>
		</plugins>
	</build>

</project>
 

2.java代码

代码如下:

/*-------------------- 主入口 -------------------------------------*/

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		
		SpringApplication.run(DemoApplication.class, args);
	}

}

/*------------------ Controller ---------------------------------------*/
package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.example.demo.config.DAO;
import com.example.demo.pojo.Book;


@Controller
public class MyController {
	
	@Autowired
	DAO dao;
	
	@GetMapping("/getRes")
	public String getRes(Model model){
		
		Book b = dao.selectByPrimaryKey("abc");
		model.addAttribute("b", b);
		System.out.println(b);
		return "index";
	}

}


/*------------------ Dao ---------------------------------------*/

package com.example.demo.config;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.example.demo.pojo.Book;


@Mapper
public interface DAO {
    Book selectByPrimaryKey(@Param("bid") String bid);
}

/*------------------Pojo ---------------------------------------*/
package com.example.demo.pojo;

import java.io.Serializable;

public class Book implements Serializable{
	private static final long serialVersionUID = 1L;
	private String bid;
	public Book(){}
	public Book(String bid) {
		this.bid = bid;
	}
	public String getBid() {
		return bid;
	}
	public void setBid(String bid) {
		this.bid = bid;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}

}
 

3.配置文件

#################### applicatin.yml ######################################
spring:
    datasource:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/test?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8
      username: root
      password: 19921201
    thymeleaf:
      prefix: classpath:/templates/
      check-template-location: true
      suffix: .html
      encoding: UTF-8
      content-type: text/html
      mode: HTML
      cache: false
    devtools:
      restart:
        enabled: true  #设置开启热部署
        additional-paths: src/main/java #重启目录
mybatis:
  mapper-locations: classpath:mapper.xml
##########################################################################

#################### logback.xml #########################################
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
    <property name="LOG_HOME" value="F:/workspace/eclipse/logs" />
    <!-- 控制台输出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>
    <!-- 按照每天生成日志文件 -->
    <appender name="FILE"  class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <FileNamePattern>${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>
    
    <!--myibatis log configure-->
    <logger name="com.apache.ibatis" level="TRACE"/>
    <logger name="java.sql.Connection" level="DEBUG"/>
    <logger name="java.sql.Statement" level="DEBUG"/>
    <logger name="java.sql.PreparedStatement" level="DEBUG"/>

    <!-- 日志输出级别 -->
    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>
</configuration>
##########################################################################


#################### 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="com.example.demo.config.DAO">

    <!-- 可根据自己的需求,是否要使用 -->
    <resultMap type="com.example.demo.pojo.Book" id="bookMap">
        <id column="bid" property="bid" jdbcType="VARCHAR" />
    </resultMap>
    
    <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="bookMap">
        select * from t_book
        where bid = #{bid,jdbcType=VARCHAR}
    </select>
</mapper>

##########################################################################

页面 index.html

<!DOCTYPE html> 
<html lang="en" xmlns:th="http://www.thymeleaf.org"> 
<head> 
    <meta charset="UTF-8"/> 
    <title>springboot-thymeleaf demo</title> 
</head> 

<body> 
    <p th:text="${b.bid}" />
</body> 
</html>

用到的jar

spring-boot-starter-thymeleaf-2.0.4.RELEASE.jar
spring-boot-starter-2.0.4.RELEASE.jar
spring-boot-starter-logging-2.0.4.RELEASE.jar
logback-classic-1.2.3.jar
logback-core-1.2.3.jar
log4j-to-slf4j-2.10.0.jar
log4j-api-2.10.0.jar
jul-to-slf4j-1.7.25.jar
javax.annotation-api-1.3.2.jar
snakeyaml-1.19.jar
thymeleaf-spring5-3.0.9.RELEASE.jar
thymeleaf-3.0.9.RELEASE.jar
attoparser-2.0.4.RELEASE.jar
unbescape-1.1.5.RELEASE.jar
slf4j-api-1.7.25.jar
thymeleaf-extras-java8time-3.0.1.RELEASE.jar
spring-boot-starter-web-2.0.4.RELEASE.jar
spring-boot-starter-json-2.0.4.RELEASE.jar
jackson-databind-2.9.6.jar
jackson-annotations-2.9.0.jar
jackson-core-2.9.6.jar
jackson-datatype-jdk8-2.9.6.jar
jackson-datatype-jsr310-2.9.6.jar
jackson-module-parameter-names-2.9.6.jar
spring-boot-starter-tomcat-2.0.4.RELEASE.jar
tomcat-embed-core-8.5.32.jar
tomcat-embed-el-8.5.32.jar
tomcat-embed-websocket-8.5.32.jar
hibernate-validator-6.0.11.Final.jar
validation-api-2.0.1.Final.jar
jboss-logging-3.3.2.Final.jar
classmate-1.3.4.jar
spring-web-5.0.8.RELEASE.jar
spring-beans-5.0.8.RELEASE.jar
spring-webmvc-5.0.8.RELEASE.jar
spring-aop-5.0.8.RELEASE.jar
spring-context-5.0.8.RELEASE.jar
spring-expression-5.0.8.RELEASE.jar
mybatis-spring-boot-starter-2.1.3.jar
spring-boot-starter-jdbc-2.0.4.RELEASE.jar
HikariCP-2.7.9.jar
spring-jdbc-5.0.8.RELEASE.jar
spring-tx-5.0.8.RELEASE.jar
mybatis-spring-boot-autoconfigure-2.1.3.jar
mybatis-3.5.5.jar
mybatis-spring-2.0.5.jar
mysql-connector-java-5.1.46.jar
spring-boot-starter-test-2.0.4.RELEASE.jar
spring-boot-test-2.0.4.RELEASE.jar
spring-boot-test-autoconfigure-2.0.4.RELEASE.jar
json-path-2.4.0.jar
json-smart-2.3.jar
accessors-smart-1.2.jar
asm-5.0.4.jar
junit-4.12.jar
assertj-core-3.9.1.jar
mockito-core-2.15.0.jar
byte-buddy-1.7.11.jar
byte-buddy-agent-1.7.11.jar
objenesis-2.6.jar
hamcrest-core-1.3.jar
hamcrest-library-1.3.jar
jsonassert-1.5.0.jar
android-json-0.0.20131108.vaadin1.jar
spring-core-5.0.8.RELEASE.jar
spring-jcl-5.0.8.RELEASE.jar
spring-test-5.0.8.RELEASE.jar
xmlunit-core-2.5.1.jar
spring-boot-devtools-2.0.4.RELEASE.jar
spring-boot-2.0.4.RELEASE.jar
spring-boot-autoconfigure-2.0.4.RELEASE.jar

效果:


总结

在thymeleaf整合中容易出现问题:比如在版本上,需要在properties中配置thymeleaf版本3.x,thymeleaf默认的文件夹为templates,页面return不需要有/,只返回页面的名称即可。

经验分享 程序员 微信小程序 职场和发展