0%

java | 代理讲解 「使用 mybatis 完整案例」

这里说的是在 spring boot 中的用法。

SQL 写在 xml 文件里面。

代理需要完成 3

  • 配置
  • 编写 xml
  • 编写接口代理文件

目录结构

1
2
3
4
5
6
7
8
9
- main
- java
- com.mybatis.test
- mapper
- UserMapper.java
- resources
- mapper
- mapper.xml
- application.properties

配置

配置文件主要是告诉 mybatisxml 位于哪里。

1
2
3
4
5
6
7
8
9
# JDBC

Spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
Spring.datasource.username=root
Spring.datasource.password=123456
Spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

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

UserMapper.java

UserEntity 是自定义的对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.mybatis.test.mapper;

import com.fate.backstage.entity.user.UserEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserMapper {

UserEntity getUser(@Param("email") String email);
}

mapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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.mybatis.test.mapper.UserMapper">
<resultMap type="com.fate.backstage.entity.user.UserEntity" id="UserInfo">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="password" column="password"/>
<result property="nickName" column="nickName"/>
<result property="email" column="email"/>
<result property="token" column="token"/>
<result property="erc20Address" column="erc20address"/>
<result property="createTime" column="create_time"/>
</resultMap>

<select id="getUser" resultType="com.fate.backstage.entity.user.UserEntity">
select * from account where
email = #{email}
</select>
</mapper>
  • namespace
    • 告诉 mybatis 依赖于哪个接口
  • resultType
    • 返回值类型是什么
请我喝杯咖啡吧~