一、第一个Mybatis案例
1.搭建数据库环境
CREATE DATABASE `mybatis`; USE `mybatis`; CREATE TABLE `user` ( `id` int(20) NOT NULL, `name` varchar(30) DEFAULT NULL, `pwd` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `user`(`id`,`name`,`pwd`) values (1,'Autumn27','123456'),(2,'法外狂徒张三','333333'),(3,'西装暴徒李四','444444')
创建好数据库后,刷新数据库
2.导入Mybatis相关jar包,推荐用Maven进行项目管理
Maven仓库:https://mvnrepository.com/
<dependencies> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.8.0-M1</version> <scope>test</scope> </dependency> </dependencies>
相关jar包:
- mybatis需要jar包:mybatis-3.5.7.jar(必备)
- mysql驱动jar包:mysql-connector-java-8.0.25.jar(必备)
- JUnit jar包:junit-jupiter-api-5.8.0-M1.jar(推荐,用于测试代码)
3.编写mybatis核心配置文件
MyBatis 的xml配置文件(configuration XML)中包含了对 MyBatis 系统的核心设置,包含获取数据库连接实例的数据源(DataSource)和决定事务作用域和控制方式的事务管理器(TransactionManager)
编写配置文件mybatis-config.xml
<?xml version="1.0" encoding="UTF8" ?> <!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.cj.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> <mappers> <mapper resource="com/autumn/mapper/UserMapper.xml"/> </mappers> </configuration>
4.编写工具类文件 MybatisUtils.java
//工具类 sqlSessionFactory 生产 sqlSession public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static{ try { //获取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(); } }
5.创建实体类及其对应Mapper接口
实体类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 + '\'' + '}'; } }
UserMapper.java
public interface UserMapper { //查询所有用户 List<User> getUserList(); }
6.编写UserMapper.xml,xml文件中存放对应的Sql语句
<?xml version="1.0" encoding="UTF8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.autumn.mapper.UserMapper"> <!-- id 等价于 重写接口的方法名 --> <!-- select标签 内写 sql语句 --> <!-- 查询所有用户 --> <select id="getUserList" resultType="com.autumn.pojo.User"> select * from mybatis.user; </select> </mapper>
其中 <mapper namespace="com.autumn.mapper.UserMapper"> 用来绑定xml对应的Mapper接口
有关select相关语句在Mybatis中文文档下的XML 映射器文件有说明。
7.编写测试文件UserMapperTest.java
查询所有用户
@Test public void testGetUserList(){ //获取sqlSession对象 SqlSession sqlSession = MybatisUtils.getSqlSession(); try{ //执行 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> userList = userMapper.getUserList(); for (User user : userList) { System.out.println(user); } }finally { //关闭sqlSession sqlSession.close(); } }