MyBatis
1.什么是MyBatis
-
Mybatis是一款优秀的持久层框架
-
它支持定制化SQL、存储过程以及高级映射
-
MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获得结果集
-
MyBatis可以使用简单的XML或注解来配置和映射原生类型、接口和Java的POJO为数据库中的记录
-
MyBatis本是apache的一个开源项目iBatis
如何获得Mybatis?
maven仓库:
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.2</version> </dependency>
2.第一个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,'张三','123456'), (2,'李四','123456');
新建项目
-
新建一个普通的maven项目
-
删除src目录
-
导入maven依赖
<!-- 导入依赖--><dependencies> <!-- mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.46</version></dependency> <!-- mybatis--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.2</version></dependency> <!-- junit--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies>
2.创建一个模块
-
编写mybatis核心配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configurationPUBLIC "-//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.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="123456"/></dataSource></environment></environments> </configuration>
-
编写mybatis工具类
//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命令所需的所有方法public static SqlSession getSqlSession() {return sqlSessionFactory.openSession();} }
3.编写代码
-
实体类
//实体类 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;} @Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", pwd='" + pwd + '\'' +'}';} }
-
Dao接口
public interface UserDao {List<User> getUserList(); }
-
接口实现类由原来的UserDaoImpl转变为一个 Mapper配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namesapce=绑定一个对应的Dao/Mapper接口--> <mapper namespace="com.zkw.dao.UserDao"><select id="getUserList" resultType="com.zkw.pojo.User">select * from mybatis.user</select> </mapper>
4.测试
MapperRegistry是什么?
核心配置文件中注册 mappers
-
junit测试
@Testpublic void test(){//第一步:获取sqlSession对象SqlSession sqlSession = MybatisUtils.getSqlSession();//方式一:执行SQLUserDao mapper = sqlSession.getMapper(UserDao.class);List<User> userList = mapper.getUserList(); for (User user : userList) {System.out.println(user);} //关闭sqlSessionsqlSession.close();}
可能遇到问题:
-
配置文件没有注册
-
绑定接口错误
-
方法名不对
-
返回类型不对
-
Maven到处资源问题
可以在pom.xml中加入:
<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>