第一个Mybatis程序
整体创建Mybatis程序的顺序:
- 创建一个普通的Maven项目
- 删除src文件
- 在pom.xml文件中配置环境,并加入过滤文件的代码
- 创建一个子项目,并在配置文件中加入过滤文件的代码
- 在resource文件夹下创建一个mybatis-config.xml配置文件,用于连接数据库
- 编写工具类,resource中是填写mybatis-config.xml配置文件的全限命名
- 编写实体类和接口类
- 编写一个用于实现接口的xml配置文件,namespace填写接口类的全限命名,id是绑定接口方法的名字,resultType填写返回值所在的全限命名
- 在mybatis-config.xml配置文件中resource加入接口实现的xml文件的全限命名。
- 测试:
- 获取Sqlsession对象
- 得到需要测试的接口类
- 测试函数
- 关闭sqlsession流
搭建环境
搭建数据库
新建项目
-
新建一个普通Maven项目
-
删除src目录
-
导入Maven依赖
-
<dependencies> <!-- mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> <!-- mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <!-- junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
创建一个模块(module)
-
编写mybatis核心配置文件(在resourse文件下创建一个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核心配置文件--> <configuration> <environments default="development"> <environment id="development"> <!-- 事务管理--> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> </configuration>
-
编写mybatis工具类
-
package 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 { //获取SqlSessionFactory对象 String resource = "org/mybatis/example/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); // SqlSession sqlSession = sqlSessionFactory.openSession(); // return sqlSession; } }
编写代码
-
实体类
-
package com.xin.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 + '\'' + '}'; } }
-
Dao接口
-
package com.xin.dao; import com.xin.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"> <!--namespace=绑定一个对应的Dao/Mapper接口--> <mapper namespace="com.xin.dao.UserDao"> <!-- id=需要绑定的方法的名字--> <select id="getUserList" resultType="com.xin.pojo.User"> select * from mybatis.user </select> </mapper>
-
测试–junit测试
注意点:
org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.
在Mybatis-config.xml文件后面加入
<mappers>
<mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>
- 注意上述代码的路径需要用斜杠,而且也是必须用斜杠,否则会出现初始化失败的错误
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QPd9t9Pa-1629010589580)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210812234750543.png)]
核心配置文件中需要注册Mapper
- xml文件里面不允许出现中文注释,否则会出现初始化错误的报错
- java.lang.ExceptionInInitializerError
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4coxA6H5-1629010589583)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210812235020975.png)]
-
需要在主配置文件中加上导入文件的代码:
-
<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>
-
否则会出现找不到xml文件的错误
测试代码:
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();
//方式一:getMapper
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}
测试结果:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xdejWoWf-1629010589584)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210812235439057.png)]