MyBatis框架学习笔记——基于注解的配置方式

基于注解的Mybatis1. 修改Dao类如下public interface IUserDao {/*** 查询所有用户* @return*/@Select("select * from user")List<User> findAll();}2. 修改SqlMapConfig.xml如下,并移除对应Dao的xml文件<!-- 告知 mybatis 映射配置的位置 --><mappers><mapper class="com.ithei
摘要由CSDN通过智能技术生成

基于注解的Mybatis

1. 修改Dao类如下

public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
List<User> findAll();
}

2. 修改SqlMapConfig.xml如下,并移除对应Dao的xml文件

<!-- 告知 mybatis 映射配置的位置 -->
<mappers>
<mapper class="com.itheima.dao"/>
</mappers>

Mybatis 注解开发

常用注解

@Insert//:实现新增
@Update//:实现更新
@Delete//:实现删除
@Select//:实现查询
@Result//:实现结果集封装
@Results//:可以与@Result 一起使用,封装多个结果集
@ResultMap//:实现引用@Results 定义的封装
@One//:实现一对一结果集封装
@Many//:实现一对多结果集封装
@SelectProvider//: 实现动态 SQL 映射
@CacheNamespace//:实现注解二级缓存的使用

示例:

public class UserDao{

/**
*在实际开发中,会遇到实体属性名与表的列名不一致的情况,可以通过配置两者的对应关系来解决
*/
@Select("select * from user")
@Results(id="userMap",
value= {
@Result(id=true,column="id",property="userId"),
@Result(column="username",property="userName"),
@Result(column="sex",property="userSex"),
@Result(column="address",property="userAddress"),
@Result(column="birthday",property="userBirthday")
})
List<User> findAll();


@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);

/**
*插入成功后返回插入数据的ID,一般适合于自增id
*/
@Insert("insert into
user(username,sex,birthday,address)values(#{username},#{sex},#{birthday},#{address}
)")
@SelectKey(keyColumn="id",keyProperty="id",resultType=Integer.class,before =
false, statement = { "select last_insert_id()" })
int saveUser(User user);
}

/**
* 查询所有账户,采用延迟加载的方式查询账户的所属用户
*/
@Select("select * from account")
@Results(id="accountMap",
value= {
@Result(id=true,column="id",property="id"),
@Result(column="uid",property="uid"),
@Result(column="money",property="money"),
@Result(column="uid",
property="user",
one=@One(select="com.itheima.dao.IUserDao.findById",
fetchType=FetchType.LAZY)
)
})
List<Account> findAll();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值