1.SqlSessionFactoryBuilder
SqlSessionFactoryBuilder作用:
- 解析配置文件:SqlSessionFactoryBuilder负责解析mybatis-config.xml配置文件中的配置信息,包括数据库连接信息、Mapper映射文件路径、插件等。
- 创建SqlSessionFactory:SqlSessionFactoryBuilder根据解析出的配置信息,创建出SqlSessionFactory对象,SqlSessionFactory是MyBatis中用于创建SqlSession对象的工厂类。
- 提供配置信息的灵活性:SqlSessionFactoryBuilder可以根据应用程序的需要,动态修改或添加mybatis-config.xml配置文件中的配置信息,以提供更灵活的配置方式。
SqlSessionFactoryBuilder的多个重载build()方法:
- build(InputStream inputStream,String environment,Properties properties)
- build(Reader reader,String environment,Properties properties)
- build(Configuration config)
build()方法中的参数environment和properties都可以为null,参数environment决定将要加载的环境,包括数据源和事务管理器﹔参数properties决定将要加载的properties文件。配置信息可以通过InputStream(字节流)、Reader (字符流).Configuration(类)三种形式提供给SqlSessionFactoryBuilder的build()方法。
2.构造SqlSessionFactory对象
通过过读取XML配置文件的方式构造SqlSessionFactory对象的关键代码如下
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
3.建议使用单例模式创建SqISessionFactory对象
SqlSessionFactory对象是线程安全的,它一旦被创建,在整个应用程序执行期间都会存在。如果我们多次创建同一个数据库的SqlSessionFactory对象,那么该数据库的资源将很容易被耗尽。通常每一个数据库都只创建一个SqlSessionFactory对象,所以在构建SqlSessionFactory对象时,建议使用单例模式。
4.SqISessionFactory
SqlSessionFactory的openSession()方法
openSession(ExecutorType execType)参数值
- ExecutorType.SIMPLE:表示为每条语句创建一条新的预处理语句。
- ExecutorType.REUSE:表示会复用预处理语句。
- ExecutorType.BATCH:表示会批量执行所有更新语句。
openSession(ExecutorType execType,Boolean autoCommit)参数值
- ExecutorType.SIMPLE:表示为每条语句创建一条新的预处理语句。
- ExecutorType.REUSE:表示会复用预处理语句。
- ExecutorType.BATCH:表示会批量执行所有更新语句。
- 参数autoCommit可设置是否开启事务。
openSession(ExecutorType execType,Connection connection)参数值
- ExecutorType.SIMPLE:表示为每条语句创建一条新的预处理语句。
- ExecutorType.REUSE:表示会复用预处理语句。
- ExecutorType.BATCH:表示会批量执行所有更新语句。
- 参数connection可提供自定义连接。
5.SqlSession
SqlSession的作用
SqlSession是MyBatis框架中另一个重要的对象,它是应用程序与持久层之间执行交互操作的一个单线程对象,主要作用是执行持久化操作,类似于JDBC中的Connection。SqlSession对象包含了执行SQL操作的方法,由于其底层封装了JDBC连接,所以可以直接使用SqlSession对象来执行已映射的SQL语句。
SqlSession对象中常用方法
SqlSession对象的使用范围
每一个线程都应该有一个自己的SqlSession对象,并且该对象不能共享。SqlSession对象是线程不安全的,因此其使用范围最好在一次请求或一个方法中,绝不能将其放在类的静态字段、对象字段或任何类型的管理范围(如Servlet的HttpSession )中使用。SqlSession对象使用完之后,要及时的关闭,SqlSession对象通常放在finally块中关闭.
6.mybatis-config.xml
<configuration>的子元素的执行顺序
<configuration>元素是整个XML配置文件的根元素,相当于MyBatis各元素的管理员。<configuration>有很多子元素,MyBatis的核心配置就是通过这些子元素完成的。需要注意的是,在核心配置文件中,<configuration>的子元素必须按照上图由上到下的顺序进行配置,否则MyBatis在解析XML配置文件的时候会报错。
7.<properties>元素
<properties>是一个配置属性的元素,该元素的作用是读取外部文件的配置信息。假设现在有一个配置文件db.properties,该文件配置了数据库的连接信息,具体如下:
<?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>
<!-- 环境配置 -->
<!-- 加载类路径下的属性文件 -->
<properties resource="db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!-- 数据库连接相关配置 ,db.properties文件中的内容-->
<dataSource type="POOLED">
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>
8.<settings>元素
<settings>元素中的常见配置参数
<settings>元素中常见配置参数的使用方式
9.<typeAliases>元素
typeAliases就是起别名的。
除了可以使用<typeAliases>元素为实体类自定义别名外,MyBatis框架还为许多常见的Java类型(如数值、字符串、日期和集合等)提供了相应的默认别名。例如别名_byte映射类型byte、_long映射类型long等,别名可以在MyBatis中直接使用,但由于别名不区分大小写,所以在使用时要注意重复定义的覆盖问题。
使用示例:
运行结果:
还有第二种方式:
这是项目源码:
pox.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>_20230328</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
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>
<!-- 环境配置 -->
<!-- 加载类路径下的属性文件 -->
<properties resource="db.properties"/>
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="true"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<!-- 第一种配置方式-->
<!-- <typeAlias type="cn.hdc.pojo.User" alias="user"></typeAlias>-->
<!-- 第二种配置方式 默认实体类名就是(不区分大小写)-->
<package name="cn.hdc.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!-- 数据库连接相关配置 ,db.properties文件中的内容-->
<dataSource type="POOLED">
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>
db.properties
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
mysql.username=root
mysql.password=666666
application.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:content="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置一下:bean注解扫描的根路径(方面后面更简单存储对象到spring容器)-->
<!-- <content:component-scan base-package="cn.hdc"></content:component-scan>-->
</beans>
usermapper.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"><!-- mapper为映射的根节点--><!-- mapper为映射的根节点,namespace指定Dao接口的完整类名 mybatis会依据这个接口动态创建一个实现类去实现这个接口, 而这个实现类是一个Mapper对象-->
<mapper namespace="cn.hdc.pojo.User">
<!--id ="接口中的方法名" parameterType="传入的参数类型" resultType = "返回实体类对象,使用包.类名"-->
<select id="findById" parameterType="int" resultType="user">
select * from users where uid = #{id}
</select>
</mapper>
user实体类:
package cn.hdc.pojo;
public class User {
private int uid;
private String uname;
private int uage;
@Override
public String toString() {
return "User{" +
"uid=" + uid +
", uname='" + uname + '\'' +
", uage=" + uage +
'}';
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public int getUage() {
return uage;
}
public void setUage(int uage) {
this.uage = uage;
}
}
数据库相关文件:
测试类:
package Test;
import cn.hdc.pojo.User;
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 org.junit.Test;
import java.io.IOException;
import java.io.Reader;
public class UserTest {
@Test
public void userFindByIdTest() {
//读取文件名
String resources = "mybatis-config.xml";
//创建流
Reader reader = null;
try {
//读取mybatis-config.xml文件内容到reader对象中
reader = Resources.getResourceAsReader(resources);
} catch (IOException e) {
e.printStackTrace();
}
//初始化mybatis数据库,创建SqlSessionFactory类的实例
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
//创建SqlSession实例
SqlSession session = sqlMapper.openSession();
//传入参数查询,返回结果
User user = session.selectOne("findById", 1);
//输出结果
System.out.println(user);
//关闭session
session.close();
}
}
项目结构:
10.<environments>元素
MyBatis可以配置多套运行环境,如开发环境、测试环境、生产环境等,我们可以灵活选择不同的配置,从而将SQL映射到不同运行环境的数据库中。不同的运行环境可以通过<environments>元素来配置,但不管增加几套运行环境,都必须要明确选择出当前要用的唯一的一个运行环境。下面是生产环境和测试环境的配置:
运行结果:
<environments>各元素配置运行环境
MyBatis的运行环境信息包括事务管理器和数据源。在MyBatis的核心配置文件中,MyBatis通过<environments>元素定义一个运行环境。<environment>元素有两个子元素,<transactionManager>元素和<daraSource>元素。<transactionManager>元素用于配置运行环境的事务管理器;<daraSource>元素用于配置运行环境的数据源信息。
<transcationManager>元素配置事务管理器
在MyBatis中,<transcationManager>元素可以配置两种类型的事务管理器,分别是JDBC和MANAGED。
- JDBC:此配置直接使用JDBC的提交和回滚设置,它依赖于从数据源得到的连接来管理事务的作用域。
- MANAGED:此配置不提交或回滚一个连接,而是让容器来管理事务的整个生命周期。默认情况下,它会关闭连接,但可以将<transcationManager>元素的closeConnection属性设置为false来阻止它默认的关闭行为。
项目中使用Spring+MyBatis,则没必要在MyBatis中配置事务管理器,实际开发中,项目会使用Spring自带的管理器来实现事务管理。对于数据源的配置,MyBatis提供了UNPOOLED、POOLED和JNDI三种数据源类型。
UNPOOLED表示数据源为无连接池类型。配置此数据源类型后,程序在每次被请求时会打开和关闭数据库连接。UNPOOLED适用于对性能要求不高的简单应用程。
UNPOOLED类型的数据源需要配置5种属性。
POOLED表示数据源为连接池类型。POOLED数据源利用“池”的概念将JDBC连接对象组织起来,节省了在创建新的连接对象时需要初始化和认证的时间。POOLED数据源使得并发Web应用可以快速的响应请求,是当前比较流行的数据源配置类型。
JNDI表示数据源可以在EJB或应用服务器等容器中使用。JNDI数据源需要配置的属性如下所示。
11.mappers>元素 (重点)
在MyBatis的核心配置文件中,<mappers>元素用于引入MyBatis映射文件。映射文件包含了POJO对象和数据表之间的映射信息,MyBatis通过核心配置文件中的<mappers>元素找到映射文件并解析其中的映射信息。通过<mappers>元素引入映射文件的方法有4种。
1.使用类路径引入
上边<typeAliases>元素就是用的这种方法,具体代码看上边
2.使用本地文件路径引入
懂得都懂,用的少。
3.使用接口类引入
- mapper标签,通过class属性指定mapper接口名称,此时对应的映射文件(UserMapper.xml)必须与接口位于同一路径下,并且名称相同
- 如mapper接口采用注解的方式,则无需映射文件
第一步先把数据库搭建好
第二步根据表名生成实体类,放在pojo这个包里,生成get,set,tostring方法
第三步创建db.properties
第四步创建UserMapper接口,申明将要实现的方法:
第五步,生成测试类:
在UserMapper这个接口 alt+insert 出现以下弹窗
第六步实现UserMapper.xml(注意这个文件在cn.hdc.mapper底下,文件路径特殊,如果不这么起包名,后面测试类会报错,找不到这个抽象类)
第七步,实现mybatis-config.xml(mappers 配置的是接口的相对路径)
第八步,运行测试类
4.使用包名引入
在使用接口类的基础上修改这一样代码即可,运行结果同上一步
- package标签,通过name属性指定mapper接口所在的包名 ,此时对应的映射文件必须与接口位于同一路径下,并且名称相同
- 如mapper接口采用注解的方式,则无需映射文件
MyBatis映射文件(就比如上边的UserMapper.xml)
MyBatis映射文件中的常用元素
<mapper>元素中namespace属性作用
- 用于区分不同的mapper,全局唯一。
- 绑定DAO接口,即面向接口编程。当namespace绑定某一接口之后,可以不用写该接口的实现类,MyBatis会通过接口的全限定名查找到对应的mapper配置来执行SQL语句,因此namespace的命名必须跟接口同名。
<mapper>元素如何区别不同的XML文件
在不同的映射文件中,<mapper>元素的子元素的id可以相同,MyBatis通过<mapper>元素的namespace属性值和子元素的id联合区分不同的Mapper.xml文件。接口中的方法与映射文件中SQL语句id应——对应。
<select>元素(接下来是select,insert,update,delete,sql,resultMap)一些知识点的讲解,在这之后会通过一个案例具体应用这些标签
示例代码:
<select>元素的常用属性
<insert>元素
示例代码:
数据库获取主键值的方式:
很多时候,执行插入操作后,需要获取插入成功的数据生成的主键值,不同类型数据库获取主键值的方式不同,下面分别对支持主键自动增长的数据库获取主键值和不支持主键自动增长的数据库获取主键值的方式进行介绍。
先看看不获取主键值的方式:
UserMapper.xml
测试类:
测试类运行结果:
数据库中的表:
如果获取了主键值,程序员能更加方便的实现之后的逻辑,如果你插入完成一条语句不返回主键值,那么你还得在从数据库中查,效率就很低。
下面看一下使用支持主键自动增长的数据库获取主键值
UserMapper.xml
这俩种方式都可以
测试类:
测试类运行结果:
这下子可以看到插入成功之后的主键回显值是7了。
数据库中的表:
结论:
下面看一下使用不支持主键自动增长的数据库获取主键值
UserMapper.xml
测试类:
测试类运行结果:
数据库中的表:
结论:
<update>元素
示例代码:
<update>元素用于映射更新语句,它可以更新数据库中的数据。在执行完元素中定义的SQL语句后,会返回更新的记录数量。使用<update>元素执行更新操作非常简单。
测试类:
运行结果:
<delete>元素
示例代码:
<delete>元素中的属性
<sql>元素
<sql>元素的作用
在一个映射文件中,通常需要定义多条SQL语句,这些SQL语句的组成可能有一部分
是相同的(如多条select语句中都查询相同的id、username字段),如果每一个SQL语句都重写一遍相同的部分,势必会增加代码量。针对此问题,可以在映射文件中使用MyBatis所
多提供的<sql>元素,将这些SQL语句中相同的组成部分抽取出来,然后在需要的地
<sql>元素的作用是定义可重用的SQL代码片段,它可以被包含在其他语句中。<sql>元素可以被静态地(在加载参数时)参数化,<sql>元素不同的属性值通过包含的对象发生变化。
测试类:
运行结果:
resultMap>元素
<resultMap>元素表示结果映射集,是MyBatis中最重要也是功能最强大的元素
<resultMap>元素主要作用是定义映射规则、更新级联以及定义类型转化器等。数据表中的列和需要返回的对象的属性可能不会完全一致,这种情况下MyBatis不会自动赋值,这时就需要使用<resultMap>元素进行结果集映射。
下面看一下具体案例:
1.创建一个t_sutdent表,并且插入几条测试数据
2.根据数据库中的表创建实体类(生成get,set,toString方法)
package cn.hdc.pojo;
public class Student {
private Integer id;
private String name;
private Integer age;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
3.创建StudentMapper接口,声明要实现的方法
package cn.hdc.mapper;
import cn.hdc.pojo.Student;
import java.util.List;
public interface StudentMapper {
public List<Student> findAllStudent();
}
4.创建StudentMapper.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"><!-- mapper为映射的根节点--><!-- mapper为映射的根节点,namespace指定Dao接口的完整类名 mybatis会依据这个接口动态创建一个实现类去实现这个接口, 而这个实现类是一个Mapper对象-->
<mapper namespace="cn.hdc.mapper.StudentMapper">
<resultMap id="studentMap" type="cn.hdc.pojo.Student">
<id column="sid" property="id"></id>
<result column="sname" property="name"></result>
<result column="sage" property="age"></result>
</resultMap>
<select id="findAllStudent" resultMap="studentMap">
select * from t_student
</select>
</mapper>
5.配置mybatis-config.xml加载StudentMapper.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>
<!-- 环境配置 -->
<!-- 加载类路径下的属性文件 -->
<properties resource="db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!-- 数据库连接相关配置 ,db.properties文件中的内容-->
<dataSource type="POOLED">
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="cn.hdc.mapper"/>
</mappers>
</configuration>
6.编写测试类
package Test;
import cn.hdc.pojo.Student;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
public class MyBatisTest {
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession;
@Before
public void init() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
sqlSession = sqlSessionFactory.openSession();
}
@Test
public void findAllStudentTest() {
List<Student> students = sqlSession.selectList("cn.hdc.mapper.StudentMapper.findAllStudent");
for (Student student : students) {
System.out.println(student);
}
}
@After
public void destory() {
sqlSession.commit();
sqlSession.close();
}
}
7.项目需要的依赖
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>_20230328</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
8.运行结果:
9.项目结构
10.db.properties
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
mysql.username=root
mysql.password=666666
11.结论:
resultMap可以解决实体类属性名与数据库表中字段名不一致的情况
封装工具类MybatisUtils
package cn.hdc.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.Reader;
public class MybaitsUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
下面看一个具体案例:员工管理系统
目标:完成一个员工管理系统,能够实现如下功能根据id查询、新增、修改、删除员工信息
1.创建工程:
2.引入依赖
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>_20230328</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
3.创建db.properties
jdbc.username=root
jdbc.password=666666
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
jdbc.driver=com.mysql.cj.jdbc.Driver
4.创建数据库,创建employee表
5.创建实体类Employee,生成get,set,toString方法
package cn.hdc.pojo;
public class Employee {
private Integer id;
private String name;
private String position;
private Integer age;
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", position='" + position + '\'' +
", age=" + age +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
6.编写MybatisUtils工具类
package cn.hdc.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.Reader;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
7.创建映射文件EmployeeMapper.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">
<mapper namespace="cn.hdc.mapper.EmployeeMapper">
<select id="findEmployeeById" parameterType="Integer" resultType="employee">
select * from employee where id = #{id}
</select>
<insert id="addEmployee" parameterType="employee">
insert into employee values (null,#{name},#{age},#{position})
</insert>
<update id="updateEmployeeById" parameterType="employee">
update employee set name=#{name},age=#{age},position=#{position} where id = #{id}
</update>
<delete id="deleteEmployeeById" parameterType="Integer">
delete from employee where id = #{id}
</delete>
</mapper>
8.实现接口EmployeeMapper.xml,声明要实现的方法
package cn.hdc.mapper;
import cn.hdc.pojo.Employee;
public interface EmployeeMapper {
public Employee findEmployeeById(Integer id);
public Integer addEmployee(Employee employee);
public Integer updateEmployeeById(Employee employee);
public Integer deleteEmployeeById(Integer id);
}
9.配置mybatis-config.xml(把EmployeeMapper.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>
<properties resource="db.properties"/>
<!-- 别名映射-->
<typeAliases>
<package name="cn.hdc.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="cn.hdc.mapper"/>
</mappers>
</configuration>
10.编写测试类:
package cn.hdc.mapper;
import cn.hdc.pojo.Employee;
import cn.hdc.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class EmployeeMapperTest {
private SqlSession session;
@Before
public void setUp() throws Exception {
this.session = MybatisUtils.getSession();
}
@After
public void tearDown() throws Exception {
this.session.close();
}
@Test
public void findEmployeeById() {
Employee employee = session.selectOne("cn.hdc.mapper.EmployeeMapper.findEmployeeById", 1);
System.out.println(employee);
}
@Test
public void addEmployee() {
Employee employee = new Employee();
employee.setName("赵六");
employee.setAge(23);
employee.setPosition("董事长");
int ret = session.update("cn.hdc.mapper.EmployeeMapper.addEmployee", employee);
if (ret > 0) {
System.out.println("添加成功!");
} else {
System.out.println("添加失败!");
}
session.commit();
}
@Test
public void updateEmployeeById() {
Employee employee = new Employee();
employee.setName("赵六");
employee.setAge(56);
employee.setPosition("员工");
employee.setId(4);
int ret = session.update("cn.hdc.mapper.EmployeeMapper.updateEmployeeById", employee);
if (ret > 0) {
System.out.println("修改成功!");
} else {
System.out.println("修改失败!");
}
session.commit();
}
@Test
public void deleteEmployeeById() {
int ret = session.delete("cn.hdc.mapper.EmployeeMapper.deleteEmployeeById", 4);
if (ret > 0) {
System.out.println("删除成功!");
} else {
System.out.println("删除失败!");
}
session.commit();
}
}
运行结果:
项目结构: