1. 导入jar包:
- mybatis-3.5.4.jar
- mysql-connector-java-5.1.45-bin.jar
2. 配置xml文件(有关数据源的一些运行环境信息)
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>
<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://localhost:3306/mybatis?useSSL=true" />
<property name="username" value="root" />
<property name="password" value="123" />
</dataSource>
</environment>
</environments>
<!-- 将sql映射文件注册到全局配置文件中 -->
<mappers>
<mapper resource="EmployeeMapper.xml" />
</mappers>
</configuration>
3. 创建sql映射文件:配置了每一个sql,以及sql的封装规则等。
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="mybatis.EmployeeMapper">
<!--
namespace: 名称空间
id: 唯一标识
resultType: 返回类型
#{id}: 从传递过来的参数中取出id值
-->
<select id="selectEmp" resultType="mybatis.bean.Employee">
select id, last_name lastName, gender, email from tbl_employee where id = #{id}
</select>
</mapper>
4. 将sql映射文件注册在全局配置文件中
mybatis-config.xml:
<!-- 将sql映射文件注册到全局配置文件中 -->
<mappers>
<mapper resource="EmployeeMapper.xml" />
</mappers>
5. 根据xml配置文件(全局配置文件)创建一个sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
6. 使用sqlSession工厂,获取到sqlSession对象来执行增删改查,一个sqlSession就代表和数据库的一次会话,用完后关闭
// 获取sqlSession实例,能直接执行已经映射的sql语句
SqlSession openSession = sqlSessionFactory.openSession();
7. 使用sql的唯一标识来告诉MyBatis执行哪个sql。sql都保存在sql映射文件中。
try {
/*
* Parameters: sql语句的唯一标识statement: Unique identifier matching the statement to
* use. 执行sql要用的参数parameter: A parameter object to pass to the statement.
*/
Employee employee = openSession.selectOne("mybatis.EmployeeMapper.selectEmp", 1);
System.out.println(employee);
} finally {
openSession.close();
}