前端之家收集整理的这篇文章主要介绍了
单一使用Mybatis, SqlSession 注意项,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是读取mybatis配置得到sqlSessionFactory的代码块
- public static org.apache.ibatis.session.sqlSessionFactory sqlSessionFactory
-
- static
- {
- String resource = "mybatis-config.xml"
- InputStream inputStream = null
- try {
- inputStream = Resources.getResourceAsStream(resource)
- sqlSessionFactory = new sqlSessionFactoryBuilder().build(inputStream)
- com.map.mapper.sqlSessionFactory.sqlSessionFactory.getConfiguration().addMapper(Map.class)
- } catch (IOException e) {
- e.printStackTrace()
- }
-
- }
这是从sqlSessionFactory 里取一个sqlSession出来保持对数据库的连接。但是这里需要特别注意的一点是在完成数据库操作后 一定要执行 session.close(); 关闭对数据库的连接。
- public List<HotSpot> getHotSpot(int merchat_id)
- {
-
- sqlSession session = com.map.mapper.sqlSessionFactory.sqlSessionFactory.openSession()
- Map map = session.getMapper(Map.class)
- List<HotSpot> hotSpot = map.getHotSpot(merchat_id)
- session.close()
- return hotSpot
- }
如果不连接会导致一个怎样的后果呢?比如下面一段代码(mapService调用的底层方法都是依赖sqlSession对数据库的操作)会导致大量的无效连接占用着数据库的连接资源,整个程序会hang住,让人感觉以为是程序的死循环,其实是 sqlSession 没有关闭导致了大量的连接一直耗费着数据库的资源而hang住了。所以我们写代码一定要注意下。
- for (Merchant chat : list_merchat) {
-
- List<HotSpot> list_hotSpot = mapService.getHotSpot(chat.getMerchat_id())
- for (HotSpot hotspot : list_hotSpot) {
- Coordinate coordinate = mapService.getCoordinate(hotspot.getCoordinate_id())
- hotspot.setHotspot_coord(coordinate)
- }
- chat.setHotspots(list_hotSpot)
- }