MyBatis是一种半自动映射的框架。需要手动匹配POJO,SQL和应映射关系,适合与一些复杂的和需要优化性能的项目。
MyBatis框架在操作数据库时,大体上经过了8个步骤
1,读取MyBatis配置文件mybatis-config.xml。mybatis-config.xml作为MyBatis的全局配置文件,配置了MyBatis的运行环境等信息以及连结数据库
2,加载映射文件Mapper.xml,该文件中配置了操作数据库的SQL语句,需要在mybatis-config.xml中加载才能执行。
3,构建会话工厂。通过MyBatis的环境等配置信息构建会话工厂SqlSessionFactory
4,创建SqlSession对象。由会话工厂创建SqlSession对象,该对象中包含了执行SQL的所有方法
5,MyBatis底层定义了一个Executor接口来操作数据库,它会构建SqlSession传递的参数动态地生成需要执行的SQl语句,同时负责查询缓存的维护
6,在Executor接口的执行方法中,包含一个MappedStatement类型的参数,该参数是对映射信息的封装
7,输入参数映射
8,输出结果映射
需要的JAR包
映射文件
<!-- 根据客户名模糊查询客户信息 -->
<select id="findCustomerByName" parameterType="String" resultType="com.itheima.po.Customer">
select * from t_customer where username like '%${value}%'
</select>
<!-- 添加客户信息 -->
<insert id="addCustomer" parameterType="com.itheima.po.Customer">
insert into t_customer(username,jobs,phone)
values(#{username},#{jobs},#{phone})
</insert>
<!-- 更新客户信息 -->
<update id="updateCustomer" parameterType="com.itheima.po.Customer">
update t_customer set
username=#{username},jobs=#{jobs},phone=#{phone}
where id=#{id}
</update>
<!-- 删除客户信息 -->
<delete id="deleteCustomer" parameterType="Integer">
delete from t_customer where id=#{id}
</delete>
核心配置文件
<?xml version="1.0" encoding="UTF-8"?><!-- 2.配置Mapper的位置 -->
<mappers>
<mapper resource="com/itheima/mapper/CustomerMapper.xml"/>
</mappers>