原文地址为:
Mybatis注解学习--xxxMapper is not known to the MapperRegistry
转载请注明本文地址: Mybatis注解学习--xxxMapper is not known to the MapperRegistry
今天晚上在学习Mybatis注解的时候,总是遇到错误Type interface com.souvi.ibatis.xxxMapper is not known to the MapperRegistry,在网上搜索相关的解决方案时,得到的答案都不怎么详细,但知道了Mybatis注解一定要注册自己写的接口类,不然就会老报开头提到的这个错误。
下面举个例子:先看看项目的简单部署吧,如图:
先看核心文件,UserTest.java
package com.rollen;
import java.io.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class UserTest {
public static void main(String[] args) {
String resource = "com/rollen/configure.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resource);
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory factory = new SqlSessionFactoryBuilder()
.build(reader);
factory.getConfiguration().addMapper(UserInfoMapper.class);
SqlSession sqlSession = factory.openSession();
try {
UserInfoMapper userInfoMapper = sqlSession
.getMapper(UserInfoMapper.class);
User user = userInfoMapper.getUser(10);
System.out.println(user);
} finally {
sqlSession.close();
}
}
}
主要要注意的是比如要注册,也就是这行代码:
factory.getConfiguration().addMapper(UserInfoMapper.class);
UserInfoMapper.java代码如下:
package com.rollen;
import org.apache.ibatis.annotations.Select;
public interface UserInfoMapper {
@Select("select * from user_tb where age= #{age}")
public User getUser(int age);
}
user.java 代码如下:
package com.rollen;
public class User {
private String name;
private int age;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
// TODO Auto-generated method stub
return "name: "+name+"age: "+age;
}
}
最后的configure.xml文件代码为:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC
"-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="User" type="com.rollen.User" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/user_db" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
参考文章:http://www.laokboke.net/2012/09/25/mybatis-annotation/
转载请注明本文地址: Mybatis注解学习--xxxMapper is not known to the MapperRegistry