mybatis document
https://mybatis.org/mybatis-3/zh/
mybatis in github
https://github.com/mybatis/mybatis-3
1. mybatis 环境搭建
这里使用maven项目构建
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- mysql 驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<!-- mybatis 框架 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
</dependencies>
2. 实体类映射文件配置(写sql)
- 实体类
package cn.bitqian.entity;
/**
* user 类
* @author echo lovely
* @date 2020/9/9 20:59
*/
public class User {
private Integer userId;
private String userName;
private String userPassword;
public User() {
}
public User(Integer userId, String userName, String userPassword) {
this.userId = userId;
this.userName = userName;
this.userPassword = userPassword;
}
// 省略set/get toString..
}
- user-mapper.xml(注意命名空间,标签 id,占位符)
<?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">
<!-- 实体类 与 sql解耦映射文件 -->
<mapper namespace="userMapper">
<!-- sql 语句 和 对应的查询结果类型 -->
<select id="selectAll" resultType="cn.bitqian.entity.User">
select * from users1
</select>
<!-- parameterType 为接收参数的类型 #{实体类属性名} 表示占位符 -->
<!-- 插入操作 需要user参数 -->
<insert id="insertUser" parameterType="cn.bitqian.entity.User">
insert into users1 values (#{userId}, #{userName}, #{userPassword})
</insert>
<!-- 修改操作 -->
<update id="updateUser" parameterType="cn.bitqian.entity.User">
update users1 set username = #{userName}, userpassword = #{userPassword}
where userid = #{userId}
</update>
<!-- 根据id删除某个user -->
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from users1 where userid = #{userId}
</delete>
</mapper>
3. mybatis核心配置文件 (环境配置)
- jdbc 连接配置
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis_study?serverTimezone=GMT
username=root
password=123456
- mybatis-config 配置 (注意头文件的引入)
<?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>
<!-- 读取jdbc.properties 配置信息 -->
<properties resource="jdbc.properties"></properties>
<environments default="development">
<!--部署环境-->
<environment id="development">
<!-- 配置事务管理器 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据源 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载映射用户 xml
这里有个小问题,cn/bitqian/mapper, 看文件夹有没三层 -->
<mapper resource="cn.bitqian.mapper/user-mapper.xml"/>
</mappers>
</configuration>
- 包名就叫cn.bitqian.mapper, 没有分层
4. 测试
- 由于初学,模板化的代码我写了四遍… 其中包含了单表curd
package DemoTest;
import cn.bitqian.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* mybatis 单表增删改查操作
* @author echo lovely
* @date 2020/9/9 21:36
*/
public class TestMybatisCurd {
// 查询单表
@Test
public void test1() {
SqlSession sqlSession = null;
try {
// mybatis 读取核心文件流
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
// 通过sql 会话工厂构建器 创建session 工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 拿到session
sqlSession = sqlSessionFactory.openSession();
// 进行查询
List<User> userList = sqlSession.selectList("userMapper.selectAll");
System.out.println(userList);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 释放session资源
if (sqlSession != null)
sqlSession.close();
}
}
@Test
public void test2() {
SqlSession sqlSession = null;
try {
// 加载mybatis核心配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
// 获得session工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 通过session工厂获得session
sqlSession = sqlSessionFactory.openSession();
User user = new User(null, "taylor swift", "gorgeous");
// 通过user-mapper 命名空间和id进行相应的sql操作
int count = sqlSession.insert("userMapper.insertUser", user);
// 进行增删改操作时 要提交事务
sqlSession.commit();
System.out.println("count = " + count);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (sqlSession != null)
sqlSession.close();
}
}
// 修改单个用户
@Test
public void test3() {
SqlSession sqlSession = null;
try {
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
sqlSession = sqlSessionFactory.openSession();
User user = new User(1, "rose", "love jack");
int count = sqlSession.update("userMapper.updateUser", user);
sqlSession.commit();
System.out.println(count);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (sqlSession != null)
sqlSession.close();
}
}
// 删除user
@Test
public void tes4() {
SqlSession sqlSession = null;
try {
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
sqlSession = sqlSessionFactory.openSession();
sqlSession.delete("userMapper.deleteUser", 1);
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (sqlSession != null)
sqlSession.close();
}
}
}