环境搭建
- jdk
- MySQL 5.7
- maven 3.6.3
- IDEA
需要掌握的知识
- JDBC
- MySQL
- Java基础
- Maven
- Junit
MyBatis
MyBatis 是一款优秀的持久层框架
MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程
MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 实体类 【Plain
Old Java Objects,普通的 Java对象】映射成数据库中的记录。
MyBatis 本是apache的一个开源项目ibatis, 2010年这个项目由apache 迁移到了google code,并
且改名为MyBatis 。
2013年11月迁移到Github .
Mybatis官方文档 : http://www.mybatis.org/mybatis-3/zh/index.html
GitHub : https://github.com/mybatis/mybatis-3
Maven:
<!-- 导入依赖-->
<dependencies>
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<!-- mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<!-- junit-->
</dependencies>
代码演示
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.导入上面的Maven
3.编写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>
<!-- 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://localhost:3306/mybatis?useSSl=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--每一个Mapper.xml都需要Mybatis核心配置文件中注册-->
<mappers>
<mapper resource="com/shadow/dao/UserMapper.xml"/>
</mappers>
</configuration>
4.编写MyBatis工具类
//sqlSessionFactory
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static{
try {
//使用Mybatis获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
5.创建实体类
package com.shadow.pojo;
public class User {
private int id;
private String name;
private String password;
public User() {
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
6.编写Mapper接口
import com.shadow.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
7.编写Mapper.xml配置文件(就像原来的UserDaoImpl)
namespace 十分重要,不能写错!
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.shadow.dao.UserDao">
<select id="getUserList" resultType="com.shadow.pojo.User">
select * from mybatis.user
</select>
</mapper>
8.编写测试类
Junit包测试
建议写在Java项目专门的Test包里面,注意要和主文件包名一样
public class UserDaoTest {
@Test
public void test() {
//第一步:获取sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//第二步:执行SQL
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭sqlSession
sqlSession.close();
}
}
9.运行测试
出现的问题
1.可能出现问题说明:Maven静态资源过滤问题<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
2.XML不能写中文的注释
解决办法:
<?xml version="1.0" encoding="UTF-8" ?>
改成
<?xml version="1.0" encoding="UTF8" ?>
3.没有在对应的XML中注册
<!--每一个Mapper.xml都需要Mybatis核心配置文件中注册-->
<mappers>
<mapper resource="com/shadow/dao/UserMapper.xml"/>
</mappers>