使用MyBatis的注解开发可以减少Mapper文件的编写,这里我们看一下:
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
这个注解代替了<id>标签和<result>标签
他里面可以配的属性有:
column:数据库的列名
property:需要装配的属性名
one:需要使用的@One注解(@Result (one=@One) () )
many:需要使用的@Many注解(@Result(many=@many) ())
@Results:可以与@Result ⼀起使⽤,封装多个结果集
代替的是<ResultMap>标签,这里注解里面可以使用单个@Result注解,也可以使用@Result集合,使用格式:@Results ({@Result (), @Result()})
@One:实现⼀对⼀结果集封装
代替了<association>标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
@One注解属性介绍:
select:指定用来多表查询的sqlmapper
使用格式:Result(column=" ", property=" ",one=@One(select=" "))
@Many:实现⼀对多结果集封装
代替了<collection>标签,是多表查询的关键,在注解中用来指定子查询返回对象集合。
使用格式:Result(property=" ",property=" ",many=@Many(select=" "))
对于上面的这些主键,这里通过一对一,一对多和多对多查询的例子看一下这些注解的使用方法
Result与One配合使用实现Mapper配置:
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.david.mapper.UserMapper.findById"))
})
List<Order> findAll();
}
Result与Many配合使用实现Mapper配置:
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.david.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);
}