string转timestamp格式 月份错误_使用YAML遇到的沙雕错误

本文记录了一次在SpringBoot项目中配置MyBatis XML扫描时遇到的问题。开发者在尝试使用XML配置Mapper时,由于配置错误导致应用无法扫描到XML文件。经过排查,错误原因是 YAML 配置文件中 MyBatis 的配置位置不正确。修复后,项目成功扫描到XML并正常运行。此外,还分享了两个关于MyBatis的常见陷阱,包括资源路径和驼峰命名映射的注意事项。
摘要由CSDN通过智能技术生成

今天搞一个小Demo的时候,卡了半小时,网上各种查资料,最后发现是个非常傻逼的错误。

想了下原因,主要是:

以前项目基本都用application.properties,自己写Demo都是用yml+通用Mapper,很少用XML。而今天yml+通用Mapper写到一半,突然想用Mapper.xml写个SQL,然后就出问题了。

具体什么问题的?后面再说。

新建一个SpringBoot项目:

c159649a1dcd2da7e041ee68ad86bf4c.png
<?xml version="1.0" encoding="UTF-8"?>
<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 https://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.7.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.bravo</groupId>
	<artifactId>time_format</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>time_format</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<dependency>
			<groupId>tk.mybatis</groupId>
			<artifactId>mapper-spring-boot-starter</artifactId>
			<version>2.1.5</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

application.yml

server:
  port: 6060

logging:
  level:
    com:
      bravo:
        debug


spring:
  datasource:
    url: jdbc:mysql:///test
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

启动类

@SpringBootApplication
@MapperScan("com.bravo") // 扫描通用Mapper接口
public class TimeFormatApplication {
	public static void main(String[] args) {
		SpringApplication.run(TimeFormatApplication.class, args);
	}
}

POJO

@Data
@Table(name = "t_time_format")
public class TimeFormat {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "SELECT LAST_INSERT_ID()")
    private Integer id;

    private String name;

    @Column(name = "timestamp_format")
    private Date timestampFormat;

    @Column(name = "datetime_format")
    private Date datetimeFormat;
}

Controller

@RestController
public class TimeController {

    @Autowired
    private TimeFormatMapper timeFormatMapper;

    /**
     * JSON提交 考察入参格式
     *
     * @param timeFormat
     * @return
     */
    @PostMapping("/postTimeJson")
    public TimeFormat PostTimeJson(@RequestBody TimeFormat timeFormat) {
        return timeFormat;
    }

    /**
     * 查询所有记录(考察返回值格式)
     *
     * @return
     */
    @GetMapping("/getAllTime")
    public List<TimeFormat> getAllTime() {
        List<TimeFormat> timeFormats = this.timeFormatMapper.selectAll();
        System.out.println(timeFormats);
        return timeFormats;
    }

}

Mapper(Service省略)

public interface TimeFormatMapper extends Mapper<TimeFormat> {
}

启动项目访问/getAllTime接口:

4b51a315ef4dc02f6f710e5917b80432.png

说明通用Mapper没问题。

然后出于某些原因,我想手写SQL,于是新建了一个TimeFormatMapper.xml:

9638d8b66983eb5e3eb8b6bf5c9f4a8b.png
<?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.bravo.timeformat.TimeFormatMapper">
    <resultMap id="BaseResultMap" type="com.bravo.timeformat.TimeFormat">
        <!--
          WARNING - @mbg.generated
        -->
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="name" jdbcType="VARCHAR" property="name"/>
        <result column="timestamp_format" jdbcType="TIMESTAMP" property="timestampFormat"/>
        <result column="datetime_format" jdbcType="TIMESTAMP" property="datetimeFormat"/>
    </resultMap>

    <!--根据时间查询-->
    <select id="getByDate" resultType="com.bravo.timeformat.TimeFormat">
        SELECT
        id, `name`, timestamp_format, datetime_format
        FROM
        t_time_format t
        <where>
            <if test="timestampFormat != null">
                and t.timestamp_format = #{timestampFormat}
            </if>
            <if test="datetimeFormat != null">
                and t.datetime_format = #{datetimeFormat}
            </if>
        </where>

    </select>

</mapper>

在Mapper接口中写了一个方法:

2ff1cb805610998ecfe3d87f3ce6030f.png

点击箭头也能跳转到XML。

在Controller中调用:

0cb4f074823aa850aa650635029c0066.png

修改application.xml,配置mapper.xml的扫描路径:

b9b9d8ebf9fa9484f9ca818a2182b0d3.png

Postman调用报错:

fb2f62fb15623e925761a420ec39d4b1.png

虽然我猜肯定是XML扫描问题,但我以为是路径写错了,检查了一下,并没有错误。application.xml中写的是classpath:mapper/*.xml,而我的XML确实在这下面:

9638d8b66983eb5e3eb8b6bf5c9f4a8b.png

XML本身namespace啥的都是对的,点击能跳转到对应的接口和POJO。

找了5分钟,没找出问题。算了,扫描不行的话就在resources下新建同名的目录吧:

e75dbc32d396a58c020f35b62ac11ec7.png

重新启动项目:

a2cc8fd4b98a8f589c7cbd368973d803.png

搞定。

但是我仍然很纠结为啥刚才扫描失败,在网上各种查,答案五花八门,我都试了一遍,没用...

后来重新把yml改成properties试了一下:

logging.level.com.bravo.timeformat=debug

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql:///test
spring.datasource.username=root
spring.datasource.password=root


spring.mvc.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

mybatis.mapper-locations=classpath:mapper/*.xml

发现能扫描到mapper/*.xml,于是肯定是yml出问题了。

重新审视yml的配置,被自己气到:

3c94002861460c7e13f57f759131d243.png

不知道为啥,mybatis配置写到了spring下面去了...当时顺着提示就回车了,看都没看光标在哪。改正后:

a834b4570c134e097a990eeae132d9aa.png

搞定了。

yml虽然提示挺强大,但太依赖格式的缩进了。我自己不是很喜欢python的代码格式,个人认为没有花括号并不意味着简洁,反而让代码的可读性下降不少。

再举例几个很久以前使用MyBatis时遇到过的坑。

坑1:

resources下建文件夹不能用.,而应该用/。

比如,我们在java目录下建多级package是这样的:

92901868b7b7d0eaffa21894c890c61e.png

但resources下你如果也这样,得到的其实是一个文件夹,而不是多级文件夹:

d074417973e6d9d0017678a36bde10e5.png

正确的做法是:

67f8fabc485fae633157fb3b6dc6b068.png

337e127993cf455b1283c7360ce0cbf2.png

坑2:

要注意数据库和POJO的驼峰映射。比如,如果我把resultMap改为resultType:

<!--根据时间查询-->
<select id="getByDate" resultType="com.bravo.timeformat.TimeFormat">
    SELECT
    id, `name`, timestamp_format, datetime_format
    FROM
    t_time_format t
    <where>
        <if test="timestampFormat != null">
            and t.timestamp_format = #{timestampFormat}
        </if>
        <if test="datetimeFormat != null">
            and t.datetime_format = #{datetimeFormat}
        </if>
    </where>

</select>

重新查询会发现时间为null:

5c6d936071e498cdf6e2ddcdce2af046.png

原因在于数据库字段是timestamp_format,而POJO是timestampFormat,会映射失败。

通用Mapper的接口是没问题的,因为通用Mapper会自动映射:

65ad19f5c50f288d089af69c74a9bb4b.png

但getByDate()这个方法的映射不是通用Mapper管的,需要我们自己手动开启MyBatis的驼峰命名:

8b95e72fca2fb06b327ac1ac7b47e976.png

2020-03-21 22:52:41

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值