思路:
-->搭建环境 (新建Maven项目)
-->在pom.xml中,导入Mybatis,mysql,Junit依赖
-->在resources文件夹中新建mybatis-config.xml文件
-->编写mybatis的工具类(MybatisUtils.java)
-->编写实体类(User.java)
-->编写Dao接口(UserDao.java)
-->编写UserMapper.xml配置文件
-->编写测试类,进行Junit测试
1.1 搭建环境搭建数据库
//创建数据库
CREATE DATABASE `mybatis`;
use `mybatis`;
//创建表
CREATE TABLE `user`(
`id` INT(20) not NULL PRIMARY KEY,
`name` VARCHAR(100) DEFAULT NULL,
`pwd` VARCHAR(50) DEFAULT NULL
)ENGINE=INNODB default CHARSET=utf8;
//插入数据
insert into user values(1,'望穿先生','123456'),(1,'张三','123456')
新建项目
1.新建一个普通的maven项目
2.删除src目录
3.导入依赖
<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<!--mysql驱动5.1.47版本的依赖5.7可以用-->
<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.5.9</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
1.2 创建一个模块
-
编写mybatis的核心配置文件 (在resources文件夹中新建mybatis-config.xml文件)
(在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"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3305/mybatis?serverTimezone=GMT&useSSL=false&useUnicode=true&characterEncoding=utf-8"/> <property name="username" value="root"/> <property name="password" value="lyl188338"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/UserMapper.xml"/> </mappers> </configuration>
-
编写mybatis的工具类(MybatisUtils.java)
//sqlsessionFactory public class MybatisUtils { //提升sqlsession的作用域 private static SqlSessionFactory sqlSessionFactory; //static代码块让他初始就去加载 static{ try { //使用mybatis获取sqlsession对象 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(); } }
- 实体类(User.java)
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 + '\'' +
'}';
}
}
- Dao接口(UserDao.java)
//此处的UserDao等价于以后的mapper
public interface UserDao {
List<User> getUserList();
}
- 接口实现类由原来的JDBC中的UserImpl转变成为一个Mapper配置文件(UserMapper.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">
<!--namesapce(命名空间)绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.lyl.dao.UserDao">
<!--select为查询语句,此处的id值为接口中的方法-->
<!--resultType为返回类型,值为要返回的实体类-->
<select id="getUserList" resultType="com.lyl.pojo.User">
select * from mybatis.user
</select>
</mapper>
1.4 测试
-
Junit测试
(测试尽量写在对应的test文件夹下,绿色的包中,并且包的结构尽量也要和上面尽可能对应)
public class UserDaoTest {
@Test
public void test() {
//第一步,获取sqlsession对象
SqlSession sqlSession = MybatisUtils.getsqlsession();
//执行sql
//方式1:通过getMapper()
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭sqlsession
sqlSession.close();
}
}
测试中可能遇到的问题:
-
错误一:找不到mybatis配置文件java.io.IOException: Could not find resource org/mybatis/example/mybatis-config.xml
解决方案:
在pom.xml中增加build
<build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
如果该方法仍然无法解决找不到配置文件的话,(1)再注意自己的mapper文件,在mybatis-config.xml配置文件中有没有注册;(2)查看自己的mybatis的工具类(MybatisUtils.java)中resources 的路径写的是否正确
-
错误二: java.lang.ExceptionInInitializerError
在mapper.xml文件中写了中文注释,导致报错
解决方案:将头文件中的
encoding="UTF-8"
改成UTF8重新运行后问题解决
-
错误三:
org.apache.ibatis.exceptions.PersistenceException:
Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure数据库连接问题
解决方案:
将mybatis-config.xml核心配置文件中
useSSL=true
改成false后问题解决<property name="url" value="jdbc:mysql://localhost:3305/mybatis?serverTimezone=GMT&useSSL=true&useUnicode=true&characterEncoding=utf-8"/>
-
错误四:
org.apache.ibatis.binding.BindingException: Type interface com.lyl.dao.UserDao is not known to the MapperRegistry.
UserMapper.xml文件中,namespace命名空间绑定问题
<mapper namespace="com.lyl.dao.UserDao">
解决方案:
查看自己的Dao/Mapper接口包的路径是否正确(路径要从java文件夹下开始写,com.xx.xx),修改正确后即可。