学习使用 Mybatis 时,碰到 Mapped Statements collection does not contain value for selectOne
异常。
代码如下: ``` public class TestEmp {
private SqlSession session;
@Before
public void before() throws IOException {
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
InputStream is = Resources.getResourceAsStream("sqlMapperConfig.xml");
SqlSessionFactory factory = builder.build(is);
session = factory.openSession();
}
@After
public void after() {
session.close();
}
@Test
public void testSelectOne() {
Emp emp = session.selectOne("selectOne");
System.out.println(emp);
}
} ``` 调用 selectOne 方法时报错,原因就是 Mybatis 没有读取到对应的方法 id,再具体一点就是在 sqlMapperConfig 文件中没有声明读取对应的 XML 映射文件。
找到 configurations
标签下的 mappers
子标签,配置 mapper
标签,设置 resource 属性为对应的实体类的 XML 映射文件即可,这样就不会报错了。
<configuration> <properties resource="jdbc.properties"/> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!--加载mapper映射文件--> <mappers> <mapper resource="mapper/EmpMapper.xml"/> </mappers> </configuration>