目标:创建一个简单的Mybatis框架的程序,实现对数据库的读取操作。
数据表user,里面有3个属性和几个数据,通过程序在console中打印出来。
开发工具:IDEA,使用maven管理资源。
思路:搭建环境—>导入Mybatis—>编写代码–>测试
一、搭建环境:
1.创建数据表
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,'张三','13212'),
(2,'李四','13sass'),
(3,'王五','ddiq132')
4.导入maven依赖
在pom.xml中加入需要的依赖包信息
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
dependencies>
过程不详细讲述,直接上最终代码。
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">
<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="prolific"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/zhang/dao/UserMapper.xml"/>
mappers>
configuration>
package com.zhang.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;
//sqlSessionFactory --->sqlSession
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();
}
}
package com.zhang.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 + '\'' +
'}';
}
}
package com.zhang.dao;
import com.zhang.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhang.dao.UserDao">
<select id="getUserList" resultType="com.zhang.pojo.User">
select * from mybatis.user
select>
mapper>
6.测试类(UserDaoTest.java)
src/test/java/com/zhang/dao/UserDaoTest.java
package com.zhang.dao;
import com.zhang.pojo.User;
import com.zhang.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();
//执行SQL
//方式一:getMapper
UserDao userDao=sqlSession.getMapper(UserDao.class);
userDao.getUserList();
List<User> userList=userDao.getUserList();
for (User user:userList){
System.out.println(user);
}
//关闭sqlSession
sqlSession.close();
}
}
运行UserDaoTest.java开始测试,
可能出现故障提示(上面对面已经不会出现这个错误):
org.apache.ibatis.binding.BindingException: Type interface com.zhang.dao.UserDao is not known to the MapperRegistry.
MapperRegistry是什么?
这个是因为Mapper.xml中没有加上Mapper资源,加上既可以解决。
<mappers>
<mapper resource="com/zhang/dao/UserMapper.xml"/>
mappers>
再运行,出现错误提示:java.lang.ExceptionInInitializerError
导致这个问题的原因:maven由于它的约定大于配置,我们的配置文件无法被导出或者生效,导致资源导出失败。
解决方法:
方法1:将src/main/resources/mybatis-config.xml文件拷贝一份到target/test-classes/com/zhang/dao/mybatis-config.xml
方法2:在父和子两个pom.xml文件中添加下面内容:
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
测试成功!
遗留问题:
我在使用方法2时,测试未成功,讲解视频是可以的,不知道哪里搞错了。
欢迎大家用上面代码测试和交流,有问题可以留言。
附学习视频资料:
视频资料链接