单一使用Mybatis, SqlSession 注意项

前端之家收集整理的这篇文章主要介绍了单一使用Mybatis, SqlSession 注意项前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这是读取mybatis配置得到sqlSessionFactory的代码

  1. public static org.apache.ibatis.session.sqlSessionFactory sqlSessionFactory;
  2.  
  3. static
  4. {
  5. String resource = "mybatis-config.xml";
  6. InputStream inputStream = null;
  7. try {
  8. inputStream = Resources.getResourceAsStream(resource);
  9. sqlSessionFactory = new sqlSessionFactoryBuilder().build(inputStream);
  10. com.map.mapper.sqlSessionFactory.sqlSessionFactory.getConfiguration().addMapper(Map.class);
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. }
  14.  
  15. }

这是从sqlSessionFactory 里取一个sqlSession出来保持对数据库的连接。但是这里需要特别注意的一点是在完成数据库操作后 一定要执行 session.close(); 关闭数据库的连接。

  1. public List<HotSpot> getHotSpot(int merchat_id)
  2. {
  3.  
  4. sqlSession session = com.map.mapper.sqlSessionFactory.sqlSessionFactory.openSession();
  5. Map map = session.getMapper(Map.class);
  6. List<HotSpot> hotSpot = map.getHotSpot(merchat_id);
  7. session.close();
  8. return hotSpot;
  9. }

如果不连接会导致一个怎样的后果呢?比如下面一段代码(mapService调用的底层方法都是依赖sqlSession对数据库的操作)会导致大量的无效连接占用着数据库的连接资源,整个程序会hang住,让人感觉以为是程序的死循环,其实是 sqlSession 没有关闭导致了大量的连接一直耗费着数据库的资源而hang住了。所以我们写代码一定要注意下。

  1. for (Merchant chat : list_merchat) {
  2.  
  3. List<HotSpot> list_hotSpot = mapService.getHotSpot(chat.getMerchat_id());
  4. for (HotSpot hotspot : list_hotSpot) {
  5. Coordinate coordinate = mapService.getCoordinate(hotspot.getCoordinate_id());
  6. hotspot.setHotspot_coord(coordinate);
  7. }
  8. chat.setHotspots(list_hotSpot);
  9. }

猜你在找的设计模式相关文章