今天晚上在學習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/