使用idea创建第一个Mybatis程序及可能遇到的问题
第一个Mybatis程序
思路:搭建环境—>导入Mybatis—>编写代码—>执行
搭建环境
创建数据库
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,'张三','zs123'),
(2,'李四','ls456'),
(3,'王五','ww789')
创建项目
****先看一下我的项目结构:
- 创建项目
- 导入Maven依赖
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
- 编写代码
创建一个Module
-
编写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> <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="1234"/> </dataSource> </environment> </environments> </configuration>
-
编写Mybatis工具类
package com.vchicken.Dao;
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.InputStream;
public class MybatisUtils {
public static SqlSessionFactory sqlSessionFactory;
static{
try {
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
编写代码
创建实体类
package com.vchicken.pojo;
public class User {
public int id;
public String name;
public 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接口
package com.vchicken.dao;
import com.vchicken.pojo.User;
import java.util.List;
public interface UserDao {
List<User> getUserList();
}
接口实现类(由UserDaoImpl文件转变为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">
<mapper namespace="com.vchicken.dao.UserDao" >
<select id="getUserList" resultType="com.vchicken.pojo.User">
select * from mybatis.user
</select>
</mapper>
测试
package com.vchicken.dao;
import com.vchicken.pojo.User;
import com.vchicken.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();
//方法一
// UserDao userDao = sqlSession.getMapper(UserDao.class);
// List<User> userList = userDao.getUserList();
//方法二,不推荐使用
List<User> userList = sqlSession.selectList("com.vchicken.dao.UserDao.getUserList");
for (User user : userList) {
System.out.println(user);
}
//关闭sqlsession
sqlSession.close();
}
}
可能遇到的问题
-
找不到config.xml文件
java.io.IOException: Could not find resource org/mybatis/example/mybatis-config.xml
- pom.xml文件中缺少以下:
<!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
-
还有一种可能就是路径错误,在封装工具类的时候,直接复制官方Mapper.xml的路径,而实际不同,所以会导致找不到文件
String resource = "org/mybatis/example/mybatis-config.xml"; //改为自己的路径即可 String resource = "mybatis-config.xml";
- 空指针异常
java.lang.NullPointerException
- 在将从 XML 文件中构建 SqlSessionFactory 的实例的过程封装为工具类的时候,出现错误
public class MybatisUtils {
public static SqlSessionFactory sqlSessionFactory;
static{
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
原因
在这里我已经把sqlSessionFactory设为一个全局的对象,而在下面又再次实例化对象,开辟新的栈空间,导致了空指针异常,修改后则代码运行正常。
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
3.出现以下错误
org.apache.ibatis.exceptions.PersistenceException:
### Error building SqlSession.
### The error may exist in com/vchicken/dao/UserMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 1 字节的 UTF-8 序列的字节 1 无效。
- 原因是:在UserMapping.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">
<!--绑定一个Dao/mapping接口-->
<mapper namespace="com.vchicken.dao.UserDao" >
<select id="getUserList" resultType="com.vchicken.pojo.User">
select * from mybatis.user
</select>
</mapper>
将中文注释去掉即可
- 出现以下错误:
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for com.vchicken.dao.UserDao.getUserList
### Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for com.vchicken.dao.UserDao.getUserList
- 原因:没有在mybatis-config.xml文件中配置文件
<mappers>
<mapper resource="com/vchicken/dao/UserMapper.xml"></mapper>//注意是自己的文件路径
</mappers>
- 运行结果