关于使用mybatis中mapper instrances,通过session另一种操作方式

 1 String resource = "mybatis-config.xml";
 2         InputStream inputStream = null;
 3         try {
 4             // 获取SqlSessionFactory
 5             inputStream = Resources.getResourceAsStream(resource);
 6             SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
 7             // 获取SqlSession
 8             SqlSession session = factory.openSession();
 9             try {
10                 //method1
11                 //Student student = session.selectOne("cn.cgq.demo.mybatis.mapper.StudentMapper.selectStudent", 10);
12                 //method2
13                 StudentMapper mapper=session.getMapper(StudentMapper.class);
14                 Student student=mapper.selectStudent(new Long(10));
15                 //输出结果
16                 System.out.println(student.toString());
17             } finally {
18                 session.close();
19             }
20         } catch (IOException e) {
21             e.printStackTrace();
22         }

在method1中可以通过SqlSession实例直接执行已映射的SQL语句

而在使用method2也是一种更直白的方式,有很多优势,首先它不是基于字符串常量的,就会更安全;

其次,如果你的 IDE 有代码补全功能,那么你可以在有了已映射 SQL 语句的基础之上利用这个功能。

使用对于给定 语句能够合理描述参数和返回值的接口(比如说BlogMapper.class),你现在不但可以执行更清晰和类型安全的代码,而且还不用担 心易错的字符串字面值以及强制类型转换。

首先需要创建一个StudentMapper的接口类,其中定义的方式,是StudentMapper.xml映射文件中的<select>标签的id属性,作为方法名,resultType作为返回值

这样代码对了,但是执行后会报错,报什么错呢

Type interface cn.cgq.demo.mybatis.bean.mapper.StudentMapper is not known to the MapperRegistry.

意思是这个接口没有注册,那么你就需要再mybatis-config.xml的配置文件中添加映射,

在<mappers>中添加<mapper class="你的那个接口类的完全包名+类名" /> //因为是class,所以跟resource不同,要用“.”

这样还是不够的,因为你还会报错

Invalid bound statement (not found): cn.cgq.demo.mybatis.bean.mapper.StudentMapper.selectStudent

就是它,说没有找到方法。在其他人的博客中说有四种情况,可能是这四种情况中出了问题


1.mapper的namespace写的不对!!!注意系修改。

2.UserDao的方法在UserDao.xml中没有,然后执行UserDao的方法会报此

3. UserDao的方法返回值是List<User>,而select元素没有正确配置ResultMap,或者只配置ResultType!

4. 如果你确认没有以上问题,请任意修改下对应的xml文件,比如删除一个空行,保存.问题解决


然而,看了看,你会发现这都对啊,没有错,。那么你的可能就是忘了为方法添加注解

@Select("select * from Student where sid=#{sid}")
public Student selectStudent(Long sid);

你没有注解是找不到这个方法的,所以会告诉你(not found),那天津爱是那个注解之后,就没什么问题了,可以正常显示

总结下来,需要这几步

1.

1 StudentMapper mapper=session.getMapper(StudentMapper.class);
2 Student student=mapper.selectStudent(new Long(10));

那当然,获得SqlSession是必须的

2.创建接口类,定义方法,方法名要和,StudentMapper.xml的配置文件<select>的id一样,返回值为resultType

3.为方法添加注解

4.添加在mybaits-config.xml文件添加类的映射

原文地址:https://www.cnblogs.com/tademeng/p/6537319.html