前言
使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。 因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句。
上面这段来自:官方文档中的 探究已映射的 SQL 语句
在MyBatis中可以使用注解来写SQL语句。用的比较少,当作扩展吧。面对简单需求用起来还是挺顺手的。
二、案例
使用注解完成增删改查。
1.实体类
User实体类
@Data
@AllArgsConstructor
public class User {
private int id;
private String name;
private String password;
private int age;
private String phone;
private String email;
}
2.接口
接口里面直接写了sql语句。
注意:如果想使用动态sql,需要加上script标签。该接口可以作为模板,需要的时候改改就好了。
官方文档在注解中使用动态sql,请查看“动态 SQL”中的“script”小节。
public interface UserMapper {
@Insert("insert into user(user_id, user_name, user_password, user_age, user_phone, user_email) " +
"values (#{id}, #{name}, #{password}, #{age}, #{phone}, #{email})")
int insUser(User u);
@Delete("delete from user where user_id = #{id}")
int delUserById(@Param("id") int id);
/** 在注解中使用动态sql */
@Delete("<script>" +
"delete from user where user_id in" +
"<foreach item='id' collection='array' open='(' separator=',' close=')'>" +
"#{id}" +
"</foreach>" +
"</script>")
int delUserByIds(String[] id);
@Update("update user " +
"set user_name=#{name},user_password=#{password},user_age=#{age},user_phone=#{phone},user_email=#{email} " +
"where user_id=#{id};")
int updUser(User u);
@Select("select * from user where user_id = #{id}")
User selUserById(@Param("id") int id);
/**
* 在注解中使用动态sql(注意:需要加上空格,不然sql语句会和参数连一起会报错)
*/
@Select("<script>" +
"select * from user" +
"<where>" +
" <if test='id != null'>and user_id = #{id}</if>" +
" <if test='name != null'>and user_name = #{name}</if>" +
" <if test='password != null'>and user_password = #{password}</if>" +
" <if test='age != null'>and user_age = #{age}</if>" +
" <if test='phone != null'>and user_phone = #{phone}</if>" +
" <if test='email != null'>and user_email = #{email}</if>" +
"</where>" +
"</script>")
List<User> selUserList(User user);
}
3.配置文件
注意,此时的配置文件,映射器中,应该使用在接口所在的包,而不是加载映射文件了!
<!-- 映射器 -->
<mappers>
<!--加载接口所在的包-->
<package name="com.slensoft.mapper"></package>
</mappers>
完整注解文档看“映射器注解”
相关
我的该分类的其他相关文章,请点击:【Spring + Spring MVC + MyBatis】文章目录