初步学习mybatis框架,学习后总结代码片段,和使用需要注意要点总结, 注意!!!!其中有个需要注意的Xml文件中有提示功能,这个功能必须要用Xml editor打开注意千万别用文本编辑器
注意!!!!其中有个需要注意的Xml文件中有提示功能,这个功能必须要用Xml editor打开注意千万别用文本编辑器打开, 用打开时一般会先跳至Design中注意左下角,点击Source即可编辑 mybatis.xml文件的配置Mapper配置(最后一个SQL语句为对trim的测试使用了一个别的表) 注意:面向接口时namespace必须为接口的完全限定名 接口 接口中最后一条@param注释是用于表示参数对应xml文件中SQl语句的哪个字段, 接口的方法名必须和Xml中SQL标签中对应的id一致 public interface StudentUsersDao { List update StudentUsers set username=#{username},password=#{password} where studentsSno=#{studentsSno} delete from StudentUsers where studentsSno=#{0} update Students sname=#{sname}, sex=#{sex}, coursesCno=#{coursesCno}, where sno=#{sno}getSUAll(); List getSUBySno(int studentsSno); List getSUByNameAndPwd(String username,String password); int updateBySno(StudentUsers studentUsers); int deleteBySno(int studentsSno); int updateStuBySno(@Param("sname")String name,@Param("sex")String sex,@Param("coursesCno")String cno,@Param("sno")int sno); } 测试 正常情况下sqlSessionFactory可以使用单例而Sqlsession一般不能使用单例, 默认情况下会启用一级缓存及sqlsession级别的缓存,同一个sqlsession下同样查询语句之间 没有增删改的情况下会存在缓存即使在其他端改变数据,仍然会查询到相同数据,这个时候可以通过 使用新的sqlsessin解决 static SqlSessionFactory sqlSessionFactory; public static void main(String[] args) throws Exception{ SqlSession session=getSqlSession(); StudentUsersDao suDao=session.getMapper(StudentUsersDao.class); System.out.println(suDao.getSUAll()); // System.out.println(suDao.getSUByNameAndPwd("余军", "123456")); // StudentUsers studentUsers=new StudentUsers("余军","123456",20141817); // System.out.println(suDao.updateBySno(studentUsers)); System.out.println("over"); // suDao.updateStuBySno(null, "ss","", 20141856); // System.out.println(suDao.deleteBySno(20141817)); // session.commit(); // System.out.println(suDao.getSUBySno(20141817)); } static{ String resource="mybatis.xml"; InputStream inputStream; try { inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); }