04.注解映射
MyBatis 注解方式
在 MyBatis 3.0 之后,即可以直接以 Annotation 方式将 SQL 与配置写在 Java 文件中,也可以直接写在 XML 文件中。笔者建议的简单的 SQL 语句可以直接以 Annotation 方式编写,复杂的 SQL 语句可以写在 XML 文件中。
public interface BlogMapper
{
@Insert('INSERT INTO BLOG(BLOG_NAME, CREATED_ON) VALUES(#{blogName}, #{createdOn})')
@Options(useGeneratedKeys=true, keyProperty='blogId')
public void insertBlog(Blog blog);
@Select('SELECT BLOG_ID AS blogId, BLOG_NAME as blogName, CREATED_ON as createdOn FROM BLOG WHERE BLOG_ID=#{blogId}')
public Blog getBlogById(Integer blogId);
@Select('SELECT * FROM BLOG ')
@Results({
@Result(id=true, property='blogId', column='BLOG_ID'),
@Result(property='blogName', column='BLOG_NAME'),
@Result(property='createdOn', column='CREATED_ON')
})
public List<Blog> getAllBlogs();
@Update('UPDATE BLOG SET BLOG_NAME=#{blogName}, CREATED_ON=#{createdOn} WHERE BLOG_ID=#{blogId}')
public void updateBlog(Blog blog);
@Delete('DELETE FROM BLOG WHERE BLOG_ID=#{blogId}')
public void deleteBlog(Integer blogId);
}
查询
结果集
插入
@Options(useGeneratedKeys = true, keyProperty = "challenge_id")
@Insert("insert into t_challenge(" +
"challenge_user_id_creator," +
"challenge_city_id)" +
"values(" +
"#{challenge_user_id_creator}," +
"#{challenge_city_id}" +
");")
public boolean insertChallenge(ChallengeResource.Entity challenge);
多行插入
@Options(useGeneratedKeys = false, keyProperty = "challengeAttendResourceList[].challenge_attend_id", keyColumn = "challenge_attend_id")
@Insert("<script>" +
"insert into t_challenge_attend (" +
"challenge_attend_challenge_id," +
"challenge_attend_user_id," +
"challenge_attend_state" +
") values " +
"<foreach collection=\"challengeAttendResourceList\" item=\"item\" index=\"index\" open=\"(\" close=\")\" separator=\"),(\">\n" +
" ${item.challenge_attend_challenge_id},\n" +
" ${item.challenge_attend_user_id},\n" +
" ${item.challenge_attend_state}\n" +
"</foreach> " +
";</script>")
public boolean insertChallengeAttendSingleOrMultiple(@Param("challengeAttendResourceList") List<ChallengeAttendResource.Entity> challengeAttendResourceList);