您的位置:首页 > 编程语言 > Java开发

Java程序加载mybatis的大致流程

2018-03-09 12:52 288 查看
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();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: