Mybatis(四)|Mybatis(四) 注解

Mybatis的注解们
Mybatis(四)|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 findAll();

【Mybatis(四)|Mybatis(四) 注解】基于注解的多对多查询
思路就是分两步查询,查出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 findUserAndRole();

RoleMapper
@Select("select * from role_user as ru,role as r where ru.roleid=r.id and ru.userid=#{id}") List findByUID(int id);

测试结果如下:
Mybatis(四)|Mybatis(四) 注解
文章图片

Mybatis(四)|Mybatis(四) 注解
文章图片

    推荐阅读