Mybatis的注解们

用例:
@Insert("INSERT INTO student(name,math,eng) VALUES (#{name},#{math}, #{eng})")
void insert(Student student);
@Delete(" delete from student where id=#{id}")
void delete(int id);
@Update("update student set name=#{name}, math=#{math}, eng=#{eng} where id =#{id}")
void update(Student student);
@Select(" select * from student where id=#{id}")
Student findByID(int id);
Results 、Result
@Select("select *,o.uid as UserID ,o.id as OrderID from user as u inner join orders as o on o.uid=u.id order by u.id")
@Results({
@Result(column = "OrderID",property = "id"),
@Result(column = "ordertime",property = "ordertime"),
@Result(column = "total",property = "total"),
@Result(column = "UserID",property = "user.id"),
@Result(column = "name",property = "user.name"),
@Result(column = "password",property = "user.password")
})
List<Order> findAll();
基于注解的多对多查询
思路就是分两步查询,查出User表中所有用户,然后再使用用户的id去和中间表和role表联查,将结果封装在User的ROLElIST中。详见下:
UserMapper接口
@Select("select * from user")
@Results({
@Result(id = true,column = "id",property = "id"),
@Result(column = "name",property = "name"),
@Result(column = "password", property = "password"),
@Result(
property = "RoleList",//放到哪里,即user类中的哪个属性
column = "id",//拿谁去查,就是用userID传参
javaType = List.class, //该属性的类型
//一对一就是@One,一对多就是@Many
many = @Many(select = "com.dao.RoleMapper.findByUID")//调用其他查询方法,该方法需要传入int id的参数
)
}
)
List<User> findUserAndRole();
RoleMapper
@Select("select * from role_user as ru,role as r where ru.roleid=r.id and ru.userid=#{id}")
List<Role> findByUID(int id);
测试结果如下:


本文详细介绍MyBatis注解的使用方法,包括增删改查基本操作、复杂查询及多对多关系处理。通过具体代码示例,展示如何利用注解实现数据库操作,为开发者提供实用的参考。
1893

被折叠的 条评论
为什么被折叠?



