要使用Mybatis需要做如下几步操作:
1. maven环境下,pom.xml依赖jar包:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
2.xml文件构建SqlSessionFactory:
每个基于mybatis的应用都是以SqlSessionFactory的实例为核心的,SqlSessionFactory实例可以通过SqlSessionFactoryBuilder获得。而SqlSessionFactoryBuilder则可以从xml配置文件或一个预先定制的Configuration的实例构建出SqlSessionFactory的实例。
从xml文件中构建SqlSessionFactory实例非常简单,建议使用类路径下的资源文件进行配置。但是也可以使用任意的输入流(InputStream)实例,包括字符串形式的文件路径或者 file:// 的 URL 形式的文件路径来配置。MyBatis 包含一个名叫 Resources 的工具类,它包含一些实用方法,可使从 classpath 或其他位置加载资源文件更加容易。
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
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>
<!--对应的sql文件-->
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
3.编写Dao(BlogMapper):
package org.mybatis.example;
public interface BlogMapper {
Blog selectBlog(int id);
}
4.测试:
public class Test{
@Test
public void test() throws Exception{
//构建SqlSessionFactory的配置文件
String resource = "org/mybatis/example/mybatis-config.xml";
//加载文件到流中
InputStream inputStream = Resources.getResourceAsStream(resource);
//根据配置文件获取
SqlSessionFactorySqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
//第一种方式:需要Dao接口 获取SqlSession
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
//第二种方式:不需要Dao接口 获取SqlSession
Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
System.out.println(blog);
}
}
}