第一步:数据库的准备,以mysql为例。
CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE USER(
id INT(11) AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) DEFAULT NULL,
psw VARCHAR(50) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO USER VALUES
(NULL,'小明','123456'),
(NULL,'小','123456'),
(NULL,'小明','123456')
第二步:配置pom.xml相关依赖
<dependencies>
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--导入mybatis环境-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- junit单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<!-- 在build中配置resuorces,如果不配置,-->
<!--则maven默认不会把我们项目下的.xml/.properties生成到target中去-->
<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>
</project>
注意:如果pom中不对build中的进行配置,测试之后报如下错,其实是因为不这样配置的话我们自己写的在java目录下的配置文件将不会生成到Target中去,故运行时就找不到该配置。
java.lang.ExceptionInInitializerError
......省略.....
Caused by: org.apache.ibatis.exceptions.PersistenceException:
### Error building SqlSession.
### The error may exist in com/hhx/dao/UserMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/hhx/dao/UserMapper.xml
没有找到资源文件UserMapper.xml
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
第三步:resources下的mybatis-config.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="development">
<!-- 开发环境-->
<environment id="development">
<!-- 默认jdbc事务管理-->
<transactionManager type="JDBC"/>
<!-- 默认数据源-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!-- 使用安全连接useSSL=true,&=&,对&符号转义;useUnicode编码,支持中文,否则乱码-->
<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="mysql123"/>
</dataSource>
</environment>
</environments>
<!--扫描配置问件的位置,-->
<mappers>
<mapper resource="com/hhx/dao/UserMapper.xml"/>
</mappers>
</configuration>
注意:如果扫描文件的位置不配置,则报如下错误:UserMapper 无法知道你配置的在MapperRegistry(mapper注册)中的UserMapper.xml
org.apache.ibatis.binding.BindingException: Type interface com.hhx.dao.UserMapper is not known to the MapperRegistry.
第四步:项目总体截图如下:
第五步:编写各个包下的代码
实体层(entity包下)代码(User.java)
注意:字段要与数据库中的一一对应。
package com.hhx.entity;
import java.io.Serializable;
/**
* @author 黄河祥
* @create 2020/2/19 10:42
*/
public class User implements Serializable {
private int id;
private String username;
private String psw;
//无参构造方法
public User() {
}
//有参构造方法
public User(int id, String username, String psw) {
this.id = id;
this.username = username;
this.psw = psw;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPsw() {
return psw;
}
public void setPsw(String psw) {
this.psw = psw;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", psw='" + psw + '\'' +
'}';
}
}
工具类utils下的MybatisUtils.java
package com.hhx.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;
/**
* @author 黄河祥
* @create 2020/2/19 11:00
* mybatis 使用
*/
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 命令所需的所有方法。
你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句*/
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
持久层(dao)下的UserMapper.java,其实相当于原来的UserDao
package com.hhx.dao;
import com.hhx.entity.User;
import java.util.List;
/**
* @author 黄河祥
* @create 2020/2/19 11:15
*/
public interface UserMapper {
//遍历数据库中的User
public List<User> getUserList();
}
持久层(dao)下的UserMapper.xml,相当于原来的UserDaoImpl
<?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接口;相当于一个dao的实现类-->
<mapper namespace="com.hhx.dao.UserMapper">
<!-- id=Dao中的方法名;resultType=返回的结果集类型,对应定义的实体类 -->
<select id="getUserList" resultType="com.hhx.entity.User">
select * from mybatis.user
</select>
</mapper>
第六步:测试
package com.hhx.dao;
import com.hhx.entity.User;
import com.hhx.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
/**
* @author 黄河祥
* @create 2020/2/19 11:29
*/
public class UserMapperTest {
@Test
public void UserDaoTest(){
//第一步:获得sqlSession
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
}
}