Java程序加载mybatis的大致流程

1.程序首先加载mybatis-config.xml配置文件,并根据配置文件的内容创建SqlSessionFactory对象

2.然后通过SqlSessionFactory对象创建SqlSession对象,SqlSession接口中定义了执行SQL语句所需要的各种方法

3.之后,通过SqlSession对象执行配置文件Mapeer.xml中定义的SQL语句,完成相应的数据操作

4.最后通过SqlSession提交事务,关闭SqlSession对象


具体实现如下所示:

public class Main {
public static void main(String[] args) throws Exception {
String resource = "com/xxx/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 加载mybatis-config.xml配置文件,并创建SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
// 创建SqlSession对象
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> parameter = new HashMap<>();
parameter.put("id",1);
// 执行select语句,将ResultSet映射成对象并返回
Blog blog = (Blog) session.selectOne("com.xxx.BlogMapper.selectBlogDetails",
parameter);
// 输出Blog对象
System.out.println(blog);
} finally {
session.close();
}
}
}

猜你喜欢

转载自blog.csdn.net/sinat_38430122/article/details/79495929