思路:搭建环境,引入mybatis–>编写代码–>测试。
1.搭建环境
1.1、创建数据库。
CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE `user`(
`id`INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(20) DEFAULT NULL,
`pwd` VARCHAR(20) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `user`(`id`, `name`, `pwd`) VALUES(1, '和尚', '12345');
INSERT INTO `user`(`id`, `name`, `pwd`) VALUES(2, '张三', '987456');
INSERT INTO `user`(`id`, `name`, `pwd`) VALUES(3, '孙悟空', '55555');
1.2、新建一个普通的maven项目。
1.3、配置pom文件,引入依赖。
<!--配置pom文件,引入所需依赖 -->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
1.4、编写mybatis核心配置文件。
- resources---->NEW---->Resource Bundle---->db.properties
driver=java.jdbc.mysql.Driver
url=jdbc:mysql://localhost:3306/mybatis
username=root
password=root
- resources/mybatis-config.xml
<!--mybatis的核心配置文件-->
<configuration>
<!--配置数据库连接 -->
<properties resource="database.properties"> </properties>
<!--配置数据库环境-->
<environments default="mysqldb">
<environment id="mysqldb">
<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>
<mapper></mapper>
</mappers>
</configuration>
1.5、编写mybatis工具类。
- 该工具类的作用:读取mybatis的配置文件,并且返回一个SQLSession(操作数据库对象,类似于statement)。
package com.ali.www.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 {
//1.使用mybatis第一步:获取sqlSessionFactory对象
//通过Resources类,获取输入流
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//通过SqlSessionFactoryBuilder()来build()一个工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//2.获取sqlSession的方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
到此为止,环境已经搭建好了。
2.编写代码
- 编写实体类
- Dao接口
- 接口对应的mapper文件【jdbc的写法是接口实现类】
2.1、实体类
package com.ali.www.pojo;
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
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 getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
2.2、UserDao接口
package com.ali.www.dao;
import com.ali.www.pojo.User;
import java.util.List;
public interface UserDao {
public List<User> getListUser();
}
2.3、接口对应的mapper文件
<?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">
<!--namespace:绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.ali.www.dao.UserDao">
<!--id:接口对应的方法。 resultType:返回类型-->
<select id="getListUser" resultType="com.ali.www.pojo.User">
select * from mybatis.user;
</select>
</mapper>
3、测试
3.1、在test目录下创建同样目录结构的UserDaoTest
3.2、编写测试类
package com.ali.www.dao;
import com.ali.www.pojo.User;
import com.ali.www.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
//通过mybatisUtils工具类,获取sqlSession
SqlSession sqlSession = MybatisUtils.getSqlSession();
//通过public abstract <T> T getMapper(Class<T> aClass)方法获取UserDao接口对象
UserDao userDaoMapper = sqlSession.getMapper(UserDao.class);
List<User> listUser = userDaoMapper.getListUser();
for (User u: listUser
) {
System.out.println(u.toString());
}
}
}
3.3、测试结果
遇到的bug:
1.org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration.
Cause: java.io.IOException: Could not find resource com/ali/www/dao/UserMapper.xml
解决办法:删除mapper标签,重新添加
2.db.properties文件的Driver配置成java.mysql.jdbc.Driver了。应该是com.mysql.jdbc.Driver
3.useSSL=false
设置成TRUE会报错
4.所有的xml文件中不能有中文注释,有中文注释会报错Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 14; 1 字节的 UTF-8 序列的字节 1 无效。
解决办法:将第一行的utf-8,改成utf8即可。