yl197837 发表于 2016-11-25 10:09:28

mybatis 第一天环境的搭建(二)

  本次通过注解的方式实现上一次的功能,为了避免观看代码的干扰,此处我把不用的代码注释掉
  1.   UserMapper.java 代码如下: UserMapper.xml 不能删除, 通过注解写SQl语句


package com.bugyun.mybatis.model;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
@Select("select * from user where id=#{id}")
public User selectUser(int i);
}
   
  2.  其他文件和上一篇博客的文件不变。
  四种Mapper的方式:

    <mappers>
<!-- 通过package元素将会把指定包下面的所有Mapper接口进行注册 -->
<package name="com.bugyun.mybatis.model"/>
<!-- 通过mapper元素的resource属性可以指定一个相对于类路径的Mapper.xml文件 -->
<mapper resource="com/bugyun/mybatis/model/UserMapper.xml"/>
<!-- 通过mapper元素的url属性可以指定一个通过URL请求道的Mapper.xml文件 -->
<mapper url="file:///E:/UserMapper.xml"/>
<!-- 通过mapper元素的class属性可以指定一个Mapper接口进行注册 -->
<mapper class="com.bugyun.mybatis.model.UserMapper"/>
</mappers>

  总结:Mybatis中定义Mapper信息有两种方式,
1. 利用xml写一个对应的包含Mapper信息的配置文件;
2. 定义一个Mapper接口,同时第二种方法有可以通过注解的方式实现功能。
页: [1]
查看完整版本: mybatis 第一天环境的搭建(二)