1.准备工作
配置mybatis-config.xml(全局配置文件)
<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"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 将我们写好的sql映射文件注册到全局配置文件中 -->
<mappers>
<mapper resource="EmployeeMapper.xml"/>
</mappers>
</configuration>
配置EmployeeMapper.xml(sql映射文件)
<!--
将这个文件写道全局配置文件中
namespace:名程空间
id:标签的唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中,取出id值
-->
<select id="selectEmp" resultType="com.atguigu.mybatis.bean.Employee">
select id,lasst_name from tbl_employee where id = #{id}
</select>
</mapper>
具体步骤
1.根据xml配制文件(mybatis-config.xml全局配置文件),通过流创建一个SqlSessionFactory对象`
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取sqlsession实例,能直接执行已经映射的sql语句
SqlSession opSession = sqlSessionFactory.openSession();
2.sql映射文件,文件中配置了每一个sql,以及sql封装规则
3.将sql映射文件注册在全局配置文件中
4.写代码:
(4.1)根据全局配置文件得到sqlsessionfactory
(4.2)根据sqlsession工厂,获取到sqlsession对象使用它来执行增删改查,一个sqlsession就是代表和数据库的一次会话,用完要关闭
(4.3)使用sql的唯一标识来告诉mybatis执行那个sql,sql都是保存在sql映射文件中的。
try {
Employee employee = opSession.selectOne("com.atguigu.mybatis.bean.EmployeeMapper.selectEmp", 1);
System.out.println(employee);
} finally {
opSession.close();
}