一. MyBatis简介
1. 什么是mybatis
-
MyBatis 是一款优秀的持久层框架 -
MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程 -
MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 实体类映射成数据库中的记录。 -
MyBatis 本是apache的一个开源项目ibatis, 2010年这个项目由apache 迁移到了google code,并且改名为MyBatis 。 -
Mybatis官方文档 : http://www.mybatis.org/mybatis-3/zh/index.html
2. 什么是持久化
持久化是将程序数据在持久状态和瞬时状态间转换的机制。
持久层:
二. MyBatis开发步骤
1. 创建数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `user`(`id`,`name`,`pwd`) values (1,'狂神','123456'),(2,'张三','abcdef'),(3,'李四','987654');
2. IDEA中导入MyBatis所需jar包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
3. pojo层下编写实体类
public class User {
private int id;
private String name;
private String pwd;
}
4. resources下编写MyBatis核心配置文件
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<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>
<mapper resource="com/pudding/dao/UserMapper.xml"/>
</mappers>
</configuration>
MyBatis核心配置文件层级关系
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8
username=root
password=root
typeAliases给实体类起别名
5. utils包下编写MyBatis工具类
在工具类中获得resources包下的mybatis核心配置文件,进而获取SqlSession连接
package com.pudding.utils;
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 java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSession(){
return sqlSessionFactory.openSession();
}
}
6. 在dao层下编写实体类的Mapper接口类
package com.pudding.dao;
import com.pudding.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
List<User> getUserList();
User getUserById(int id);
User getUserById(Map<String,Object> map);
int addUser(User user);
int addUser2(Map<String,Object> map);
int updateUser(User user);
int deleteUser(int id);
}
7. 编写实体类对应的Mapper.xml配置文件
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pudding.dao.UserMapper">
<select id="getUserList" resultType="com.pudding.pojo.User">
select * from user
</select>
<select id="getUserById" parameterType="int" resultType="com.pudding.pojo.User">
select * from user where id = #{id}
</select>
<select id="getUserById2" parameterType="map" resultType="com.pudding.pojo.User">
select * from user where id = #{id} and name = #{name}
</select>
<insert id="addUser" parameterType="com.pudding.pojo.User">
insert into user (id, name ,pwd) value (#{id},#{name},#{pwd});
</insert>
<update id="updateUser" parameterType="com.pudding.pojo.User">
update user set name=#{name},pwd=#{pwd} where id = #{id}
</update>
<delete id="deleteUser" parameterType="com.pudding.pojo.User">
delete from user where id = #{id}
</delete>
</mapper>
mybatis映射文件概述
7.1 Mybatis的Dao(Mapper)层实现
8. 通过测试类进行测试
package com.pudding.dao;
import com.pudding.pojo.User;
import com.pudding.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void testfindAll(){
SqlSession sqlSession = MybatisUtils.getSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getUserList();
for(User user : userList){
System.out.println(user);
}
sqlSession.close();
}
@Test
public void tsetSelectUserById() {
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
session.close();
}
@Test
public void testAddUser() {
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User(4,"王五","zxcvbn");
int i = mapper.addUser(user);
System.out.println(i);
session.commit();
session.close();
}
@Test
public void testUpdateUser() {
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
mapper.updateUser(new User(4, "哈哈", "123123"));
session.commit();
session.close();
}
@Test
public void testDeleteUser() {
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int i = mapper.deleteUser(4);
System.out.println(i);
session.commit();
session.close();
}
}
9. 注意事项
Maven中的build下要配置静态资源过滤问题
<?xml version="1.0" encoding="UTF8"?>
<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">
<parent>
<artifactId>Mybatis-Study</artifactId>
<groupId>com.pudding</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mybatis-01</artifactId>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
三. MyBatis相应的API
1. SqlSessionFactoryBuilder(SqlSession工厂构建器)
2. SqlSessionFactory(SqlSession工厂对象)
3. SqlSession(会话对象)
|