当前位置: 首页 > news >正文

Mybatis_day4_Mybatis的注解开发

  • 这几年来注解开发越来越流行,Mybatis 也可以使用注解开发方式,这样我们就可以减少编写 Mapper 映射文件。

mybatis 的常用注解说明

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

使用 Mybatis 注解实现基本 CRUD

  1. 编写实体类
public class User implements Serializable {
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;public Integer getUserId() {return userId;
}
public void setUserId(Integer userId) {this.userId = userId;
}
.....
  • 注意:此处User的属性名和数据库表的列名不一致。

  1. 使用注解方式开发持久层接口
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@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();/**
* 根据 id 查询一个用户
* @param userId
* @return
*/
@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);/**
* 保存操作
* @param user
* @return
*/
@Insert("insert into user(username,sex,birthday,address)values(#{username},#{sex},#{birthday},#{address})")
int saveUser(User user);/**
* 更新操作
* @param user
* @return
*/
@Update("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id =#{id} ")
int updateUser(User user);/**
* 删除用户
* @param userId
* @return
*/
@Delete("delete from user where id = #{uid} ")
int deleteUser(Integer userId);/**
* 查询使用聚合函数
* @return
*/
@Select("select count(*) from user ")
int findTotal();/**
* 模糊查询
* @param name
* @return
*/
@Select("select * from user where username like #{username} ")
List<User> findByName(String name);
}

  1. 编写 SqlMapConfig 配置文件

<!-- 配置映射信息 -->
<mappers><!-- 配置 dao 接口的位置,它有两种方式
第一种:使用 mapper 标签配置 class 属性
第二种:使用 package 标签,直接指定 dao 接口所在的包
--><package name="cn.myp666.dao"/>
</mappers>



使用注解实现复杂关系映射开发

  • 实现复杂关系映射之前我们可以在映射文件中通过配置<resultMap>来实现,在使用注解开发时我们需要借助@Results 注解,@Result 注解,@One 注解,@Many 注解。

复杂关系映射的注解说明
  • @Results 注解

    • 代替的是标签<resultMap>
    • 该注解中可以使用单个@Result 注解,也可以使用@Result 集合
      • @Results({@Result(),@Result()})或@Results(@Result())
  • @Result 注解

    • 代替了<id>标签和<result>标签
    • @Result 中 属性介绍:
      • id 是否是主键字段
      • column 数据库的列名
      • property 需要装配的属性名
      • one 需要使用的@One 注解(@Result(one=@One)()))
      • many 需要使用的@Many 注解(@Result(many=@many)()))
  • @One注解(一对一)

    • 代替了<assocation>标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
    • @One 注解属性介绍:
      • select 指定用来多表查询的 sqlmapper
      • fetchType 会覆盖全局的配置参数
      • lazyLoadingEnabled。。
    • 使用格式:
      • @Result(column=" “,property=” “,one=@One(select=” "))
  • @Many注解(多对一)

    • 代替了<Collection>标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。
    • 注意:聚集元素用来处理“一对多”的关系。需要指定映射的 Java 实体类的属性,属性的 javaType(一般为 ArrayList)但是注解中可以不定义;
    • 使用格式:
      • @Result(property=" “,column=” “,many=@Many(select=” "))

使用注解实现一对多复杂关系映射
  1. 添加账户的持久层接口并使用注解配置
public interface IAccountDao {
/**
* 查询所有账户,采用延迟加载的方式查询账户的所属用户
* @return
*/
@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="cn.myp666.dao.IUserDao.findById",fetchType=FetchType.LAZY)
)
})
List<Account> findAll();
}

  1. 添加用户的持久层接口并使用注解配置
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@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();/**
* 根据 id 查询一个用户
* @param userId
* @return
*/
@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);
}


使用注解实现一对多复杂关系映射
  1. 编写用户的持久层接口并使用注解配置
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@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"),@Result(column="id",property="accounts",many=@Many(select="cn.myp666.dao.IAccountDao.findByUid",fetchType=FetchType.LAZY))})List<User> findAll();
}
  • @Many:相当于<collection>的配置
  • select 属性:代表将要执行的 sql 语句
  • fetchType 属性:代表加载方式,一般如果要延迟加载都设置为LAZY的值

  1. 编写账户的持久层接口并使用注解配置
public interface IAccountDao {
/**
* 根据用户 id 查询用户下的所有账户
* * @param userId
* @return
*/
@Select("select * from account where uid = #{uid} ")
List<Account> findByUid(Integer userId);
}



mybatis 基于注解的二级缓存

  1. 在 SqlMapConfig 中开启二级缓存支持
<!-- 配置二级缓存 -->
<settings>
<!-- 开启二级缓存的支持 --><setting name="cacheEnabled" value="true"/>
</settings>
  1. 在持久层接口中使用注解配置二级缓存
@CacheNamespace(blocking=true)//mybatis 基于注解方式实现配置二级缓存
public interface IUserDao {}

http://www.taodudu.cc/news/show-1476406.html

相关文章:

  • 对rust语言的一些理解
  • 基于单片机的智能安防系统设计(32+4G+WIFI版)-设计说明书
  • ANSYS Maxwell16 引导
  • 【ARMv8/v9 系统寄存器 6 -- EL 异常等级判定寄存器 CurrentEL 使用详细将介绍】
  • 【35分钟掌握金融风控策略28】贷中模型体系策略应用
  • 降Compose十八掌之『亢龙有悔』
  • Mybatis遇坑
  • 关于java中的位运算
  • Spring_day1
  • Spring_day2
  • Spring_day3
  • Spring_day4
  • SpringMVC_day1
  • SpringMVC_day1_常用注解
  • SpringMVC_02
  • Error creating bean with name 'dataSource' defined in class path resource [spring/spring-dao.xml]:
  • SpringSecurity入门
  • 服务注册不进eureka
  • Spring Cloud总结
  • 在此之前的博客地址
  • golang利用反射写入excel的简单工具类
  • 实习工作难点记录
  • c 结构体之位域(位段)
  • 辗转相除求最大公约数,最大公倍数
  • Ubuntu“无法解析或打开软件包的列表或是状态文件”的解决办法。
  • 错误:cc1: error: unrecognized command line option “-m32”
  • 在编写mini2440 helloworld驱动遇到的问题
  • [leetcode] Median of Two Sorted Arrays 寻找两个有序数组的中位数
  • [leetcode] Reverse Integer 反转一个整数
  • [leetcode] Palindrome Number 回文数判断
  • [leetcode] Longest Common Prefix 字符窜最长公共前缀判断
  • [leetcode] Single Number 查找数组中的单数
  • [leetcode] Power of Two 判断一个数是否是2的平方
  • [leetcode] Max Points on a Line 判断最多有多少个点在同一条直线上
  • 使用selenium webdriver进行元素定位
  • 一个动态增长的栈实现