什么是MyBatis
MyBatis框架的前身是Apache的一个开源项目,名称为iBaits。2010年,该项目迁移到了Google,更名为MyBatis。2013年,项目又交由GitHub托管。MyBatis在三层架构中处于Dao层,用于访问数据库。其作用类似于JDBC。为开发者减少了许多工作。
MyBatis框架的下载
我们要从GitHub官网下载MyBaits框架mybatis的下载,下载mybatis的相关jar包和源码
MyBatis框架的环境搭建
- 导入MyBatis的相关jar包和数据库驱动包
- mybatis所需的配置文件,其中包括主配置文件和映射配置文件,文件名任意命名,我这里将主配置文件命名为mybatis.xml,将映射配置文件命名为mapper.xml
- 导入日志相关的配置文件
MyBatis-jar包的简单介绍和xml文件的相关配置
-
相关jar包:
- mybatis框架的核心jar包mybatis-3.4.6.jar(该版本为3.4.6,具体版本请以官网为准)
- mybatis的依赖jar包:
- ant-1.9.6.jar
- ant-launcher-1.9.6.jar
- asm-5.2.jar
- cglib-3.2.5.jar
- javassist-3.22.0-GA.jar
- 以上是和动态代理相关的jar包
- -------------------------------------------------------------------------------------------------------------------
- log4j-1.2.17.jar
- log4j-api-2.3.jar
- log4j-core-2.3.jar
- slf4j-api-1.7.25.jar
- slf4j-log4j12-1.7.25.jar
- commons-logging-1.2.jar
- 以上jar是和日志技术相关的jar包(这里不再做详细介绍)
- -------------------------------------------------------------------------------------------------------------------
-
xml文件的配置和常用标签的介绍
-
mybatis.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属性文件,在该文件中可以对运行环境进行配置,例如:数据库连接的四个参数 dirver url username password
也可以配置一些数据库连接池的一些参数
-->
<properties resource="jdbc.properties" />
<typeAliases>
<!-- 为实体类指定别名 -->
<!-- <typeAlias type="com.abc.beans.Student" alias="Student"/> -->
<!-- 为指定包中的所有类指定别名,别名为该类的简单类名 -->
<package name="com.abc.beans"/>
</typeAliases>
<!-- 配置运行环境 -->
<!-- default为默认的运行环境 这里是mysql-->
<environments default="mysqlEM">
<environment id="mysqlEM">
<transactionManager type="JDBC" />
<!-- transactionManager该标签用于指定事务管理器。
type的取值有两个:
JDBC:使用JDBC事务管理器
MANAGED:使用第三方事务管理器,例如使用Spring的事务管理器
-->
<!--
<dataSource type="POOLED">
该标签用于指定数据源类型。type的取值有三个:
POOLED:使用连接池技术(默认使用的是Mybatis内置连接池)
UNPOOLED:不使用连接池技术
JNDI:Java Naming-Directory Interface,Java命名与目录接口,这是一个容器。
-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" /> <!-- "${key}"对第12行引入的配置文件进行引用方式 value中也可以直接写属性值 -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
<environment id="oracleEM">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!-- 注册映射文件 -->
<mappers>
<!-- <mapper resource="com/abc/dao/mapper.xml" /> -->
<!-- 下面的方式可以使映射文件存放到本地文件系统,但此方式不常用 -->
<!-- <mapper url="file:///e:/mapper.xml"/> -->
<!-- 使用下面的注册方式需要满足以下三点要求:
1) 映射文件要与Dao接口在同一个包下
2) 映射文件名要与Dao接口的简单类名相同
3) 映射文件的<mapper/>标签的namespace属性值为Dao接口的全限定性类名
满足以上三个条件,那么这里的class属性值就可以填写Dao接口的全限定性类名
-->
<mapper class="com.abc.dao.IStudentDao"/>
<!-- 使用下面的注册方式需要满足以下四点要求:
1) 映射文件要与Dao接口在同一个包下
2) 映射文件名要与Dao接口的简单类名相同
3) 映射文件的<mapper/>标签的namespace属性值为Dao接口的全限定性类名
4) 使用动态Mapper
满足以上四个条件,那么这里的name属性值就可以填写Dao接口所在的包名
-->
<!-- <package name="com.abc.dao"/> -->
</mappers>
</configuration>
-
mapper.xml的相关配置
- 该文件主要是映射JDBC的增删改查操作
<?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="com.abc.dao.IStudentDao">
<insert id="insertStudent">
insert into student(name,age,score) values(#{name}, #{age}, #{score})
</insert>
<insert id="insertStudentCatchId">
insert into student(name,age,score) values(#{name}, #{age}, #{score})
<selectKey resultType="int" keyProperty="id" order="AFTER">
<!-- resultType返回结果的类型 keyProperty主键属性 order是指该语句与insert语句执行的先后顺序 -->
<!-- select @@identity 查询系统属性 查询到id以后并封装到传入的对象中 -->
select last_insert_id()
</selectKey>
</insert>
<!-- 当动态参数类型为基本数据类型或String时,#{}的作用仅仅是个占位符,其中填写什么内容都可以
当动态参数类型为自定义类型的对象时,#{}中填写的是该对象的属性名
-->
<delete id="deleteById">
delete from student where id=#{xxx}
</delete>
<update id="updateStudent">
update student set name=#{name}, age=#{age}, score=#{score} where id=#{id}
</update>
<!-- resultType与resultMap指的是查询出的每一条记录所要封闭的对象类型,并非查询的结果集类型 -->
<select id="selectAllStudent" resultType="Student">
select id,name,age,score from student
</select>
<select id="selectStudentById" resultType="Student">
select id,name,age,score from student where id=#{ooo}
</select>
<select id="selectStudentsByName" resultType="Student">
<!-- select * from student where name like '%张%' -->
select id,name,age,score from student where name like '%' #{jjj} '%'
<!-- select id,name,age,score from student where name like concat('%', #{jjj}, '%') -->
<!-- select id,name,age,score from student where name like '%${value}%' -->
</select>
<select id="selectStudentsByCondition" resultType="Student">
select id,name,age,score from student where name like '%' #{name} '%' and age < #{age}
</select>
<select id="selectStudentsByCondition2" resultType="Student">
<!-- select id,name,age,score from student where name like '%' #{cname} '%' and age < #{cage} -->
select id,name,age,score from student where name like '%' #{stu1.name} '%' and age < #{stu2.age}
</select>
<select id="selectStudentsByCondition3" resultType="Student">
select id,name,age,score from student where name like '%' #{0} '%' and age < #{1}
</select>
<!-- 总结
#{}中可写填写什么内容:
1)参数对象的属性
2)任意内容,参数对象为基本数据类型或String时,起占位符作用
3)map的key
4)map的key的属性,当map的key为对象时
-->
</mapper>
环境搭建好以后我们开始实现第一个mybatis程序吧
- 该demo我们实现数据的插入操作
- 首先我们创建一个jdbc的properties文件,配置一下数据库连接的相关参数
- 在mybatis.xml中引入该属性文件,引入方式<properties resource="jdbc.properties" />,详细请见上边代码
- 创建Student实体类,和数据库相关表。
- 创建业务接口IStudentDao,并添加方法void insertStudent(Student student);
- 创建Dao接口实现类
1.jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///test
username=root
password=111(填自己数据库的密码)
2.mybatis.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="jdbc.properties" ></properties>
<!-- 配置运行环境 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql:///test" />
<property name="username" value="root" />
<property name="password" value="yc00125" />
</dataSource>
</environment>
</environments>
<!-- 注册映射文件 -->
<mappers>
<mapper resource="com/abc/dao/mapper.xml" />
</mappers>
</configuration>
3.Dao接口
package com.abc.dao;
import com.abc.beans.Student;
public interface IStudentDao {
void insertStudent(Student student);
}
4.Dao实现类 (后期可用mapper动态代理,我们就不用再写实现类)
package com.abc.dao;
import java.io.IOException;
import java.io.InputStream;
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 com.abc.beans.Student;
public class StudentDaoImpl implements IStudentDao {
@Override
public void insertStudent(Student student) {
SqlSession session = null;
try {
// 1. 创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
// 2. 加载主配置文件
InputStream is = Resources.getResourceAsStream("mybatis.xml");
// 3. 创建SqlSessionFactory
SqlSessionFactory factory = builder.build(is);
// 4. 创建SqlSession对象
session = factory.openSession();
// 5. 执行命令
session.insert("insertStu", student);
// 6. SqlSession的提交
session.commit();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 7. SqlSession的关闭
if (session != null) {
session.close();
}
}
}
}
5.编写测试类,我们的程序就可以运行了
package com.abc.test;
import com.abc.beans.Student;
import com.abc.dao.IStudentDao;
import com.abc.dao.StudentDaoImpl;
public class MyTest {
public static void main(String[] args) {
Student student = new Student("张三", 23, 93.5);
IStudentDao dao = new StudentDaoImpl();
dao.insertStudent(student);
}
}