第一个Mybatis程序
思路:搭建环境–>导入jar包或者依赖–>编写代码–>测试
2.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,'yang','123456'),
(2,'张三','123456'),
(3,'李四','334455')
新建项目
-
新建一个普通的maven项目
-
删除src目录
-
添加mybatis,mysql连接,junit的依赖
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.48</version> </dependency> </dependencies>
2.2 创建一个模块
在项目里面创建maven的moudule模块
-
在moudule的resources目录下创建一个名为mybatis-config的xml文件,下面的是官方的模板
**创建文件注意:**如果是用IDEA创建此文件,最好在创建file类的时候直接写上后缀名,不然有可能在项目中全名找不到文件
注意:不能有中文出现在配置文件,注释也不行<configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> </configuration>
-
执行sql语句需要sqlSession这个对象,SqlSession 提供了在数据库执行 SQL 命令所需的所有方法,我们需要从SqlSessionFactory中获取,SqlSession相当于JDBC的statement对象
编写mybatis工具类:获得SqlSession 对象package com.yang.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 MybatisUtil { private static SqlSessionFactory sqlSessionFactory;//提升作用域 static {//初始化的时候的加载SqlSessionFactory对象 try { String resource = "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对象 } }
2.3 编写代码
-
实体类
package com.yang.POJO; public class User { private int id; private String name; private String pwd; public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } public User() { } 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; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }
-
Dao接口
package com.yang.DAO; import com.yang.POJO.User; import java.util.List; public interface UserDao { List<User> getUserList(); }
-
接口实现类,之前是通过编写实现类,而现在只需要编写配置文件
<?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.yang.DAO.UserDao"> <!-- id对应接口里面的方法,resultType对应返回列表的泛型--> <select id="getUserList" resultType="com.yang.POJO.User"> select * from mybatis.user </select> </mapper>
-
注册mapper,在mybatis的核心配置文件mybatis-config.xml中注册
<mappers> <mapper resource="com/yang/DAO/UserMapper.xml"/> </mappers>
-
可能会出现配置文件不能导出到目标文件夹的问题,在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>
- 编写测试类
package com.yang.DAO;
import com.yang.POJO.User;
import com.yang.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class test {
@Test
public void test1(){
SqlSession sqlSession=null;
try{
sqlSession = MybatisUtil.getSqlSession();//通过工具类获得SqlSession对象
UserDao mapper = sqlSession.getMapper(UserDao.class);//通过SqlSession获得dao层接口的mapper
List<User> userList = mapper.getUserList();//可以调用接口的方法了
for (User user : userList) {
System.out.println(user);
}
}
finally {
sqlSession.close();
}
}
}
注意问题:
- 配置文件没有注册
- 绑定接口错误
- mapper对应的方法名不对
- 返回类型不对
- maven资源导出问题