MyBatis Mapper详解
Mapper.xml
- ⭐statement标签:select、update、delete、insert分别对应查询、更新、删除、插入操作
- ⭐parameterType:参数数据类型
- 基本数据类型,通过id查询Account
<select id="findById" parameterType="long" resultType="com.oyrf.frist.Account">
select * from t_account where id = #{id}
</select>
- String类型,通过name查询Account
<select id="findByName" parameterType="java.lang.String" resultType="com.oyrf.frist.Account">
select * from t_account where username = #{username}
</select>
- 包类型,通过id查询Account
<select id="findById2" parameterType="java.lang.Long" resultType="com.oyrf.frist.Account">
select * from t_account where id = #{id}
</select>
- 多个参数,通过name和age查询Account
可能会报以下错误:
### Error querying database. Cause: org.apache.ibatis.binding.BindingException: Parameter 'username' not found. Available parameters are [arg1, arg0, param1, param2]
原因是输入参数的时候不可以用#{username}和#{age}
<select id="findByNameAndAge" resultType="com.oyrf.frist.Account">
select * from t_account where username = #{username} and age = #{age}
</select>
应该用arg1, arg0, param1, param2
<select id="findByNameAndAge" resultType="com.oyrf.frist.Account">
select * from t_account where username = #{param1} and age = #{param2}
</select>
- Java Bean
<update id="update" parameterType="com.oyrf.frist.Account">
update t_account set username = #{username},password = #{password},age = #{age} where id = #{id}
</update>
- ⭐resultType:结果类型
- 基本数据类型,统计Account总数
<select id="count" resultType="int">
select count(id) from t_account
</select>
- 包装类,统计Accoun总数
<select id="count2" resultType="java.lang.Integer">
select count(id) from t_account
</select>
- String类型,通过id查询Account的name
<select id="findNameById" parameterType="long" resultType="java.lang.String">
select username from t_account where id = #{id}
</select>
- Java bean
<select id="findById" parameterType="long" resultType="com.oyrf.frist.Account">
select * from t_account where id = #{id}
</select>