Mybatis支持注解和xml配置文件混合使用的方式,可以方便的切换使用,单使用注解可以比较方便快捷的实现一些简单的SQL语句,其用法是在接口里的方法上,直接使用注解的方式进行设定。
可以通过注解实现查询、插入、更新、联合查询等。
注:若列名中存在关键字则使用反引号包裹。
单表查询返回列表
@Results({
@Result(column = "sid",property = "sid",id = true),
@Result(column = "name",property = "name"),
@Result(column = "sex",property = "sex"),
@Result(column = "age",property = "age")
})
@Select("select * from student")
List<Students> getStudents();
多表联合查询
@Results({
@Result(column = "id",property = "id",id = true),
@Result(column = "sid",property = "students",one = @One(select = "getStudent")),
@Result(column = "bid",property = "books",one = @One(select = "getBook"))
})
@Select("select * from borrow")
List<Borrow> getBorrow();
@Select("select * from student where sid=#{sid}")
Students getStudent(int sid);
@Select("select * from book where bid=#{bid}")
Books getBook(int bid);
多参数SQL操作,多参数时需要使用@Param注解指明当前属性所对应的参数名称。
@Update("UPDATE book SET title = #{title},`desc` = #{desc},price=#{price} WHERE bid = #{bid}")
int updateBookInfo(@Param("title")String title,@Param("desc")String desc,@Param("price")double price,@Param("bid")int bid);
@Delete("Delete from book WHERE bid = #{bid}")
int deleteBookInfo(@Param("bid")int bid);
@Insert("INSERT INTO book(`bid`, `title`, `desc`, `price`) VALUES (NULL, #{title}, #{desc}, #{price})")
int insertBookInfo(@Param("title")String title,@Param("desc")String desc,@Param("price")double price);
@Select("select * from book")
@Results({
@Result(property = "bid",column = "bid"),
@Result(property = "title",column = "title"),
@Result(property = "desc",column = "desc"),
@Result(property = "price",column = "price"),
})
List<Book> getBookAllInfo();