1.导入相关jar包;
![](https://i-blog.csdnimg.cn/blog_migrate/bb6310317afe824f730c14357a8b5b82.png)
2.在项目根目录下创建Mybatis.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>
<mappers>
<mapper resource="com/oracle/mapper/UserMapper.xml" /> //引入UserMapper,以此来实现ORM-对象关系映射的中键连接环节。
</mappers>
</configuration>
3.创建包名
com.oracle.mapper
在里面创建UserMapper接口。
package com.oracle.mapper;
import com.oracle.pojo.Users;
public interface UserMapper {
//声明进行操作user表的方法
Users selectUserById(Integer id);
}
4.在
com.oracle.mapper
中创建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 namespace="com.oracle.mapper.UserMapper">
//此id对应的使相同名称接口类下的方法 //传入参数类型 //返回值类型
<select id="selectUserById" parameterType="int" resultType="com.oracle.pojo.Users">
//此方法下的id
select * from users where id = #{id}
</select>
</mapper>
5.创建测试类test.java实现main方法;
package com.oracle.test;
import java.io.IOException;
import java.io.Reader;
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.oracle.mapper.UserMapper;
import com.oracle.pojo.Users;
public class Test {
public static void main(String[] args) throws IOException {
String resource = "mybatis.xml";
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = ssf.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Users selectUserById = mapper.selectUserById(1);
System.err.println(selectUserById);
sqlSession.close();
}
}