1、创建web项目
2、再pom.xml中引入mybatis的相关依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
3、在项目中的resource目录下创建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="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
4、创建mapper映射文件
<?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="mapper.Usermapper">
<select id="finduser" resultType="pojo.User"> select * from user </select>
</mapper>
5、创建mapper接口,并关联映射文件
package mapper;
import pojo.User;
public interface Usermapper {
User finduser();
}
注意:关联时要保持两个一致
1.映射文件中sql语句的id要与mapper接口名保持一致
2.映射文件中的namespace要与接口的全路径保持一致
6、创建测试类进行查询测试
public class MybatisTest {
@Test
public void fun() throws IOException {
//通过流来读取mybatis的xml配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
//创建构建工厂类对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//构建sqlsession工厂类对象
SqlSessionFactory build = sqlSessionFactoryBuilder.build(resourceAsStream);
//sqlsession是与数据库之间的会话对象
SqlSession sqlSession = build.openSession();
//获取mapper代理对象
Usermapper mapper = sqlSession.getMapper(Usermapper.class);
//通过mapper对象去查找用户
List<User> finduser = mapper.finduser();
System.out.println(finduser);
}
}