Mybatis study notes 10 notes

Mybatis provides an annotation development method to replace the Mapper.xml file. We can directly use annotations to complete the definition and binding of SQL.

Annotate the specific steps of development:

1. Add annotations to the methods of the DAO interface

    @Select("select id,username,password,gender,regist_time as registerTime from t_user")
    List<User> queryUsers();

2. Modify the registration method in the main configuration file

<mapper class="com.zt.DAO.UserDAO"/>

Annotation method of conditional query:

    @Select("select id,username,password,gender,regist_time as registerTime\n" +
            "    from t_user" +
            "    where id = #{id}")
    User queryUserById(@Param("id") Integer id);

Annotation way to delete:

    @Delete("delete from t_user\n" +
            "        where id = #{id}")
    Integer deleteUserById(@Param("id") Integer id);

Updated annotation method:

    @Update("update t_user\n" +
            "        set username = #{username},password = #{password},gender = #{gender},regist_time = #{registerTime}\n" +
            "        where id = #{id}")
    Integer updateUser(User user);

Insert annotation method:

    @Insert("insert into t_user values(#{id},#{username},#{password},#{gender},#{registerTime})")
    Integer insertUser(User user);

[Important] Comments on the primary key backfill:

    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into t_user values(#{id},#{username},#{password},#{gender},#{registerTime})")
    Integer insertUser(User user);

useGeneratedKeys indicates whether the self-incremented keyProperty indicates the attribute column to be backfilled

It is worth noting that although annotations save the trouble of defining mapper.xml files, annotations are not as flexible as mapper.xml files, such as setting resultMap, etc. At the same time, SQL and code will be coupled together.

 

Guess you like

Origin blog.csdn.net/qq_39304630/article/details/112303591