目录
实现步骤总结:
- Maven 工程中导入 MyBatis 和 MySQL 的依赖
- 创建实体类,推荐类名和表名一致,该类的对象用于对应表的一行数据
- 创建持久层的 dao 接口(也可以称为持久层的 mapper 接口),定义操作数据库的方法
- 创建 SQL 映射文件 xxxDao.xml (一个 dao 接口对应一个 SQL 映射文件),该文件用于写 SQL 语句
- SQL 映射文件需要与 dao 接口在同一目录(也可以在 resources 目录下,但是不推荐)
- SQL 映射文件名称需要和 dao 接口文件名称保持一致
- 创建 MyBatis 的主配置文件
- 获取 MyBatis 操作数据库的会话对象 SqlSession ,通过
getMapper()
(后面讲)获取接口的动态代理实现类 - 逻辑测试
入门实例
1、创建 MySQL数据库和表
数据库名 ssm ,表名 student
CREATE TABLE `student` (
`id` int(11) NOT NULL ,
`name` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2、创建 Maven 工程
3、加入 Maven 坐标
pom.xml 加入 MyBatis 和 MySQL 的依赖:
<dependencies>
<!-- 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/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
4、资源插件
mapper.xml 文件一般是放在 resources 目录下,但是在 MyBatis 工程中为了便于查看和管理 SQL映射文件,它一般放在 dao 包下。所以为了能让 Maven 识别到非 resources 目录下的资源文件,要在 pom.xml 中加入资源插件。
<build>
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
6、创建实体类 Student
对应 1、 的表,在 pojo 包中创建 Student 类
package com.bjpowernode.pojo;
/**
* Description: 实体类
*/
public class Student {
//属性名和列名一样
private Integer id;
private String name;
private String email;
private Integer age;
// set ,get , toString
}
7、编写 dao 接口 StudentDao
package com.bjpowernode.dao;
public interface StudentDao {
// 查询所有数据
List<Student> selectStudents();
// 插入一个学生信息
int insertStudent(Student student);
int updateStudent(Student student);
int deleteStudent(int id);
}
8、编写 dao 接口的 SQL 映射文件
在dao包中创建 StudentDao.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">
<!--
namespace:必须有值,自定义的唯一字符串
推荐使用: dao 接口的全限定名称
-->
<mapper namespace="com.bjpowernode.dao.StudentDao">
<!--
<select>: 查询数据, 标签中必须是 select 语句
id: sql 语句的自定义名称,推荐使用 dao 接口中方法名称,使用名称表示要执行的 sql 语句
resultType: 查询语句的返回结果数据类型,使用全限定类名
-->
<select id="selectStudents" resultType="com.bjpowernode.domain.Student">
<!--要执行的 sql 语句-->
select id,name,email,age from student
</select>
<insert id="insertStudent">
insert into student values (#{id},#{name},#{email},#{age})
</insert>
<update id="updateStudent">
update student set age = #{age} where id=#{id}
</update>
<delete id="deleteStudent">
delete from student where id=#{studentId}
</delete>
</mapper>
9、创建 MyBatis 主配置文件 mybatis-config.xml
项目 src/main 下创建 resources 目录,设置 resources 目录为 resources root,创建主配置文件:名称为 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>
<!--配置 mybatis 环境,可以有多个环境-->
<environments default="mysql">
<!--environment:一个数据库信息的配置-->
<!--id:数据源的名称,唯一值,可自定义-->
<environment id="mysql">
<!--配置事务类型:使用 JDBC 事务(使用 Connection 的提交和回滚) -->
<transactionManager type="JDBC"/>
<!--数据源 dataSource:创建数据库 Connection 对象
type: POOLED 使用数据库的连接池
-->
<dataSource type="POOLED">
<!--连接数据库的四个要素-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--告诉 mybatis 要执行的 sql 语句的位置-->
<!--可以有多个-->
<mapper resource="com/bjpowernode/dao/StudentDao.xml"/>
</mappers>
</configuration>
10、创建测试类 MyBatisTest
在 src/test/java/com/bjpowernode/ 下创建 MyBatisTest.java 文件,这里先使用 MyBatis 的传统 DAO 实现的方式。
@Test
public void testStart() throws IOException {
// 1.mybatis 主配置文件
String config = "mybatis-config.xml";
// 2.读取配置文件
InputStream in = Resources.getResourceAsStream(config);
// 3.创建 SqlSessionFactoryBuilder 对象,目的是获取 SqlSession
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
// 4.创建 SqlSessionFactory 对象
SqlSessionFactory factory = builder.build(in);
// 5.获取 SqlSession,SqlSession 能执行 sql 语句
SqlSession session = factory.openSession();
// 6.指定要执行的 sql 语句的标识 = SQL映射文件中的 namespace + "." + 标签的id
String sql = "com.bjpowernode.dao.StudentDao.selectStudents";
// 7.执行 SqlSession 的 selectList()
List<Student> studentList = session.selectList(sql);
// 8.循环输出查询结果
studentList.forEach( student -> System.out.println(student));
String sql2 = "com.bjpowernode.dao.StudentDao.insertStudent";
Student student = new Student(1005, "张三", "48569@163.com", 36);
int rows = session.insert(sql2, student);
session.commit();
sout("执行插入操作后,数据库受影响的行数");
student.setAge(37);
rows = session.update("com.bjpowernode.dao.StudentDao.updateStudent", student);
session.commit();]
sout("执行更新操作后,数据库受影响的行数" + rows);
int id = 1001;
rows = session.delete("com.bjpowernode.dao.StudentDao.deleteStudent", id);
session.commit();
System.out.println("删除操作后,数据库受影响的行数:"+rows);
// 9.关闭 SqlSession,释放资源
session.close();
}
11、配置日志功能
mybatis-config.xml 文件加入日志配置,可以在控制台输出执行的 sql 语句和参数
<!--控制 MyBatis全局行为-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>