一、Mybatis在控制台程序中的演示示例
1、创建sqlSession数据库语句执行对象
Reader reader=Resources.getResourceAsReader("resourse.xml"); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession=sqlSessionFactory.openSession(); 2、执行sql查询 StudentEntity studentEntity=new StudentEntity(); studentEntity.setS_name("小"); studentEntity.setS_age(18); List list=sqlSession.selectList("dynamicSelect3", studentEntity); System.out.println(list.size()); 3、结果遍历输出到控制台 for(int i=0;i<list.size();i++){ StudentEntity student2=(StudentEntity) list.get(i); System.out.println("s_name名称"+student2.getS_name()); } 二、mybatis事务在新增操作的时候,默认是需要使用sqlSession.commit();来向数据库提交数据,不然新增的数据只提交到了缓存里面,并没有完成数据库数据的新增。
代码见以下示例:
StudentEntity student4=new StudentEntity(); String s_name="小泽玛利亚"; student4.setS_name(s_name); student4.setS_age(18); student4.setS_id(UUID.randomUUID().toString().replace("-", "")); student4.setS_loginName("132"); student4.setS_passWord("123456"); sqlSession.insert("insert",student4); sqlSession.commit(); 三、mybatis缓存机制简单介绍1、一级缓存
mybatis在创建SQLSession对象的时候就默认开启了以及缓存,当SQLSession关闭或者执行清空缓存时,缓存会清空,此时将不能再使用上一次执行的操作缓存。
也就是说,如果在两次相同的查询中间执行了缓存清空,第二次查询就无法从缓存里面使用第一次查询的结果。
2、二级缓存
在二级缓存使用时,需要在实体类的配置文件里面配置<cache>标签。
查看mybatis详细信息的童鞋请移步:《深入理解mybatis原理》 MyBatis的一级缓存实现详解 及使用注意事项