Mybatis Hello World
大约 1 分钟
Mybatis Hello World
基于Spring Boot框架实现一个Mybatis的Hello World实例
关于spring boot的相关知识,这里不在赘述
首先引入Maven依赖,这里同时引入了mybatis的starter和mysql的驱动包
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
数据库以及相关表已经建立好了,建表语句如下:
CREATE TABLE `learn`.`Untitled` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '??',
`name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '???',
`phone` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '???',
`email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '??',
`profession` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '??',
`age` tinyint UNSIGNED NULL DEFAULT NULL COMMENT '??',
`gender` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '?? , 1: ?, 2: ?',
`status` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '??',
`createtime` datetime NULL DEFAULT NULL COMMENT '????',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 25 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '?????' ROW_FORMAT = Dynamic;
配置数据源
spring:
datasource:
url: jdbc:mysql://localhost:3306/learn
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
配置映射文件路径
mybatis:
mapper-locations: classpath*:/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.xul.mybatis.mapper.UserMapper">
<select id="selectUser" resultType="com.xul.mybatis.model.UserModel">
select * from tb_user where id = #{id}
</select>
</mapper>
编写mapper接口
@Mapper
public interface UserMapper {
UserModel selectUser(int id);
}
启动后直接调用接口,就可以达到返回值了