<mapper namespace="com.emerson.learning.dao.ICommunicatorDao">
<select id="getById" parameterType="int" resultType="Communicator">
select * from communicator where communicator_id=#{id}
</select>
<select id="getAll" resultType="Communicator">
select * from communicator order by communicator_name
</select>
</mapper>
接口定义好了,那么如何将映射文件中的select / insert / update / delete 等元素与代理接口中的方法绑定呢?其实很简单,只需要在代理接口中定义一些方法,并以相应元素的id属性值做为方法名,parameterType属性值做为方法参数类型,属性resultType值做为方法的返回值即可。下面定义的两个方法就分别对应上面映射文件中的两个select元素。
public interface ICommunicatorDao {
public Communicator getById(int id);
public List<Communicator> getAll();
}
有些朋友会问了,接口定义好了,是不是还要再定义一个实现类呢?答案是否定的。Mybatis会使用动态代理机制来帮助我们完成额外的工作,我们需要做的就是把这个接口注册到Mybatis中。在Mybatis的总配置文件中,加入如下语句。
public interface ICommunicatorDao {
@Select("SELECT * FROM communicator WHERE communicator_id=#{id}")
public Communicator getById(@Param(value = "id") int id);
@Select("SELECT * FROM communicator ORDER BY communicator_id")
public List<Communicator> getAll();
}