结合官方文档,试了一下 MyBatis 原生使用。源码已上传到 github
https://github.com/ConstXiong/toy/tree/master/demo/mybatis
1、maven 依赖,MySQL驱动 + MyBatis 3.5.5
<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>constxiong</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>mybatis</artifactId>
<dependencies>
<!-- MySQL 8.0.21 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
</dependencies>
<build>
</build>
</project>
2、MyBatis 配置文件 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://172.31.32.184:3306/constxiong?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="constxiong@123"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="constxiong/mapper/UserMapper.xml"/>
</mappers>
</configuration>
3、写 SQL 的 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="constxiong.mapper.UserMapper">
<select id="selectUser" resultType="constxiong.po.User" parameterType="constxiong.po.User">
select * from user where id = #{id}
</select>
<insert id="insertUser" parameterType="constxiong.po.User">
insert into user values(#{id}, #{name})
</insert>
</mapper>
4、Mapper 接口类,结合使用了 @Select
package constxiong.mapper;
import constxiong.po.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* UserMapper 接口,映射对数据库的操作
*/
public interface UserMapper {
public User selectUser(int id);
public int insertUser(User user);
@Select("select * from user")
public List<User> selectAllUsers();
}
5、User PO 模型
package constxiong.po;
/**
* 用户表模型
*/
public class User {
private Integer id;
private String name;
public User(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
6、测试 MyBatis xml 与 注解的使用
ConstXiong 备案号:苏ICP备16009629号-3