搭建环境
- 1,搭建数据库
DROP DATABASE IF EXISTS `mybatis`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int NOT NULL,
`name` varchar(30),
`pwd` varchar(30),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8i;
INSERT INTO `user` VALUES ('1', '张三', '123456');
INSERT INTO `user` VALUES ('2', '李四', '456');
INSERT INTO `user` VALUES ('3', '王五', '123');
- 2,创建Maven项目
- 导入mysql驱动,mybatis,与junit等依赖
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>MyBatis-Study</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<!--junit依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<!--开启过滤器,让其在编译的时候把配置文件也加入target中-->
<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>
- 3,编写SqlSession工厂类
- 注意,工厂类需要使用到mybatis-config.xml文件:即mybatis核心配置文件
- 作用:
- 构建SqlSessionFactory:意为SqlSession工厂
- 返回SqlSession
package com.kuang.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;
// Sql Session Factory :SQL会话工厂类
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();
}
}
- 4,编写一个mybatis核心配置文件
<?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核心配置文件-->
<configuration>
<!--environments可以配置多套环境-->
<environments default="development">
<environment id="development">
<!--事物管理,此处事物管理使用的时JDBC的-->
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--数据库相关的东西-->
<property name="driver" value="com.mysql.jdbc.Driver"/><!--驱动注册-->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/><!--jdbc连接数据库的URL-->
<property name="username" value="root"/><!--链接用户-->
<property name="password" value="123456"/><!--链接密码-->
</dataSource>
</environment>
</environments>
</configuration>
- 5,编写User实体类,对应数据库的表
package com.kuang.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 + '\'' +
'}';
}
}
- 6,构建接口(dao接口)
package com.kuang.dao;
import com.kuang.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
- 7,接口实现类
- 接口实现类由原来的UserDaoImpl转换为Mapper.xml配置文件
- 即(dao接口)实现类是一个Mapper.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">
<!--namespace=绑定对应的Dao/Mapper接口-->
<mapper namespace="com.kuang.dao.UserMapper">
<!--查询语句,id绑定接口中的方法
resultType意为返回集,这里将返回值返回设置为com\kuang\pojo\User类-->
<select id="getUserList" resultType="com.kuang.pojo.User">
SELECT * FROM mybatis.user
</select>
</mapper>
测试
package com.kuang.dao;
import com.kuang.pojo.User;
import com.kuang.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
// 第一步:获取SqlSession对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//方式1:getMapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
// 关闭sqlSession
sqlSession.close();
}
}
总结
当我们把SqlSessionFactory对象创建好之后,我们只需要在UserMapper接口中添加方法,然后在UserMapper.xml配置文件中增加对应的sql标签与sql语句即可完成之前我们在dao层的所有工作。
- UserMapper.xml配置文件
- 在maven中,我们需要开启过滤器,不然maven会将配置文件过滤掉
<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>