文章目录
MyBatis注解开发
1.1 MyBatis的常用注解
1.2 配置注解
修改MyBatis的核心配置文件,我们使用了注解替代的映射文件,所以我们只需要加载使用了注解的Mapper接口即可
<mappers>
<mapper class="com.itheima.mapper.UserMapper">
mapper>
mappers> 或者指定扫描包含映射关系的接口所在的包也可以 <mappers>
<package name="com.itheima.mapper">
package>
mappers>
1.3 MyBatis的注解实现复杂映射开发
@Results
代替的是标签
该注解中可以使用单个@Result注解,也可以使用@Result集 合。使用格式:@Results({@Result(),@Result()})或@Results(@Result())
@Resut
代替了
标签和
标签 @Result中属性介绍: column:数据库的列名 property:需要装配的属性名 one:需要使用的@One 注解(@Result(one=@One)())) many:需要使用的@Many 注解(@Result(many=@many)()))
@One (一对一)
代替了
标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。 @One注解属性介绍: select: 指定用来多表查询的 sqlmapper 使用格式:@Result(column=" ",property="",one=@One(select=""))
@Many (多对一)
代替了
标签, 是是多表查询的关键,在注解中用来指定子查询返回对象集合。 使用格式:@Result(property="",column="",many=@Many(select=""))
mybatis 基于注解方式实现配置二级缓存
1.4 实例
1.4.1 一对一
一对一模型 在前面mybatis的封装结果集中有这一对一
public interface OrderMapper {
@Select("select * from orders") @Results({
@Result(id=true,property = "id",column = "id"), @Result(property = "ordertime",column = "ordertime"), @Result(property = "total",column = "total"), @Result(property = "user",column = "uid", javaType = User.class, one = @One(select = "com.itheima.mapper.UserMapper.findById")) }) List<Order> findAll(); }
public interface UserMapper {
@Select("select * from user where id=#{id}") User findById(int id); }
1.4.2 一对多
public interface UserMapper { @Select("select * from user") @Results({ @Result(id = true,property = "id",column = "id"), @Result(property = "username",column = "username"), @Result(property = "password",column = "password"), @Result(property = "birthday",column = "birthday"), @Result(property = "orderList",column = "id", javaType = List.class, many = @Many(select = "com.itheima.mapper.OrderMapper.findByUid")) }) List
findAllUserAndOrder(); }
public interface OrderMapper { @Select("select * from orders where uid=#{uid}") List
findByUid(int uid); }
1.4.3 多对多
public interface UserMapper {
@Select("select * from user") @Results({
@Result(id = true,property = "id",column = "id"), @Result(property = "username",column = "username"), @Result(property = "password",column = "password"), @Result(property = "birthday",column = "birthday"), @Result(property = "roleList",column = "id", javaType = List.class, many = @Many(select = "com.itheima.mapper.RoleMapper.findByUid")) }) List<User> findAllUserAndRole(); }
public interface RoleMapper {
@Select("select * from role r,user_role ur where r.id=ur.role_id and ur.user_id=#{uid}") List<Role> findByUid(int uid); }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/207101.html原文链接:https://javaforall.net
