MyBatis简单应用
# MyBatis简单应用
本文的MyBatis简单应用是指Maven工程项目仅仅使用MyBatis操作数据库,而不使用Spring整合MyBatis。
参考:
# POM引入依赖
相关依赖最新版本见官方地址或Maven仓库地址。
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--MySQL Drive-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>runtime</scope>
</dependency>
<!--Unit Test-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--Log-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
# 创建User数据表
create table user
(
id int auto_increment primary key,
username varchar(32) null,
password varchar(32) null
);
# 编写User实体类
public class User {
private int id;
private String username;
private String password;
// setter getter toString ...
}
# 编写映射⽂件UserMapper.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="userMapper">
<select id="findAll" resultType="org.example.hello.mybatis.entity.User">
select * from User
</select>
</mapper>
# 编写核⼼⽂件SqlMapConfig.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="dev">
<environment id="dev">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
# 测试类测试
public class MyBatisTest {
@Test
public void testSelectAll() throws IOException {
// 加载核⼼配置⽂件
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// 获得sqlSession⼯⼚对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 获得sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执⾏sql语句
List<User> userList = sqlSession.selectList("userMapper.findAll");
// 打印结果
System.out.println(userList);
// 释放资源
sqlSession.close();
}
}
# 其他CURD
# 插⼊
编写 UserMapper
映射⽂件:
<insert id="add" parameterType="org.example.hello.mybatis.entity.User">
insert into user(username, password) values(#{username}, #{password})
</insert>
测试类方法:
@Test
public void testAdd() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setUsername("jacky");
user.setPassword("123456");
// 执⾏sql语句
int insert = sqlSession.insert("userMapper.add", user);
System.out.println(insert);
sqlSession.commit();
// 释放资源
sqlSession.close();
}
插⼊操作注意问题:
- 插⼊语句使⽤
insert
标签 - 在映射⽂件中使⽤
parameterType
属性指定要插⼊的数据类型 - Sql语句中使⽤
#{实体属性名}
⽅式引⽤实体中的属性值 - 插⼊操作使⽤的API是
sqlSession.insert("namespace.id", obj)
- 插⼊操作涉及数据库数据变化,使⽤sqlSession对象时需要显示提交事务,即
sqlSession.commit()
# 修改
编写 UserMapper
映射⽂件:
<update id="update" parameterType="org.example.hello.mybatis.entity.User">
update user set username = #{username}, password = #{password} where id = #{id}
</update>
测试类方法:
@Test
public void testUpdate() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setId(3);
user.setUsername("jack");
user.setPassword("1234567");
// 执⾏sql语句
int update = sqlSession.update("userMapper.update", user);
System.out.println(update);
sqlSession.commit();
// 释放资源
sqlSession.close();
}
更新操作注意问题的问题基本与插入一致,区别就是使⽤update
标签以及使用的API改为 sqlSession.update("namespace.id", obj)
。
# 删除
编写 UserMapper
映射⽂件:
<delete id="delete" parameterType="java.lang.Integer">
delete from user where id= #{id}
</delete>
测试类方法:
@Test
public void testDeleted() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
// 执⾏sql语句
int delete = sqlSession.update("userMapper.delete", 3);
System.out.println(delete);
sqlSession.commit();
// 释放资源
sqlSession.close();
}
删除操作注意问题的问题也与上述操作相似,区别如下:
- •删除语句使⽤
delete
标签 - Sql语句中使⽤
#{任意字符串}
⽅式引⽤传递的单个参数
- 删除操作使⽤的API是
sqlSession.delete("namespace.id", obj)
# 常用API介绍
# SqlSessionFactoryBuilder
SqlSessionFactoryBuilder(SqlSession工厂构建器)常用API:SqlSessionFactory build(InputStream inputStream)
,通过加载MyBatis的核心文件的输入流以构建一个SqlSessionFactory对象。示例如下:
String resource = "org/mybatis/builder/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
// 常用 API
SqlSessionFactory factory = builder.build(inputStream);
其中, Resources 工具类在 org.apache.ibatis.io
包中,帮助我们从类路径下、文件系统或一个 Web URL 中加载资源文件。
# SqlSessionFactory
SqlSessionFactory(SqlSession工厂对象)有多个方法创建SqlSession实例。常用的有如下两个:
方法 | 说明 |
---|---|
openSession() | 默认开启一个事务,但事务不会自动提交。意味着需要手动提交事务,更新操作的数据才会持久到数据库中 |
openSession(boolean autoCommit) | 对比上面的方法,提供了是否自动提交事务的参数。如果autoCommit为ture,那么会自动提交事务 |
# SqlSession
SqlSession(会话对象)在MyBatis中是非常强大的一个类。在这里你会看到所有执行语句、提交或回滚事务和获取映射器实例的方法。
// 执行语句的方法主要有:
<T> T selectOne(String statement, Object parameter)
<E> List<E> selectList(String statement, Object parameter)
int insert(String statement, Object parameter)
int update(String statement, Object parameter)
int delete(String statement, Object parameter)
// 操作事务的方法主要有:
void commit()
void rollback()
# Mybatis的Dao层实现
# 传统开发方式
编写UserDao接口
public interface UserDao {
List<User> findAll() throws IOException;
}
编写UserDaoImpl实现
public class UserDaoImpl implements UserDao {
public List<User> findAll() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> userList = sqlSession.selectList("userMapper.findAll");
sqlSession.close();
return userList;
}
}
测试用例:
@Test
public void testTraditionDao() throws IOException {
UserDao userDao = new UserDaoImpl();
List<User> all = userDao.findAll();
System.out.println(all);
}
# 代理开发方式
采用 MyBatis 的代理开发方式实现 DAO 层的开发,是我们后面进入企业的主流开发方式。
Mapper 接口开发方法只需要程序员编写 Mapper 接口(相当于Dao接口),由MyBatis 框架根据接口定义创建接口的动态代理对象,代理对象的方法体 同上边Dao接口实现类方法。 Mapper 接口开发需要遵循以下规范:
- Mapper.xml文件中的namespace与Mapper接口的全限定名相同
- Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
- Mapper接口方法的输入参数类型和Mapper.xml中定义的每个sql的parameterType的类型相同
- Mapper接口方法的输出参数类型和Mapper.xml中定义的每个sql的resultType的类型相同
范例见上几小节的内容,测试代理方式:
@Test
public void testProxyDao() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
// 获得MyBatis框架生成的UserMapper接口的实现类
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.findById(1);
System.out.println(user);
sqlSession.close();
}