绝?数查询场景可以使? resultType 进?返回,如下代码所示:
它的优点是使??便,直接定义到某个实体类即可
<select id="getbyUserid" resultType="com.example.mybatis3.entity.Userinfo">
select * from userinfo where id =${id}
</select>
resultMap 使?场景:
字段名和属性名不同的情况
使用场景:
实现实体类中的属性 和 字段映射的功能
<resultMap id="userMap" type="com.example.mybatis3.entity.Userinfo">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="photo" property="photo"/>
</resultMap>
<select id="getbyUserid" resultMap="userMap">
select * from userinfo where id =${id}
</select>
当实体类属性名与数据库中名字不一致时:
例子:
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into userinfo(
username,
password
<if test="updateTime != null">
,updatetime
</if>
)values(
#{username},
#{password}
<if test="updateTime != null">
,#{updatetime}
</if>)
</insert>
效果:
trim 通常配合 if 来用
如果所有字段都是?必填项
标签中有如下属性:
例子:
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into userinfo
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="username != null">
username,
</if>
<if test="password != null">
password,
</if>
<if test="photo != null">
photo,
</if>
</trim>
values
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="username != null">
#{username},
</if>
<if test="password != null">
#{password},
</if>
<if test="photo != null">
#{photo},
</if>
</trim>
</insert>
效果:
传?的?户对象,根据属性做 where 条件查询,?户对象中属性不为 null 的,都为查询条件。
where 可以去除 最前面的 and
标签也可以使? 替换
例:
<select id="getListByParm" resultType="com.example.mybatis3.entity.Userinfo">
select * from userinfo
<where>
<if test="username != null">
username = #{username}
</if>
<if test="password != null">
and password = #{password}
</if>
</where>
</select>
效果:
根据传?的?户对象属性来更新?户数据,可以使?标签来指定动态内容
<update id="upUser">
update userinfo
<set>
<if test="username != null">
username = #{username},
</if>
<if test="password != null">
password = #{password},
</if>
</set>
where id=#{id}
</update>
以上标签也可以使? 替换
对集合进?遍历时可以使?该标签。标签有如下属性:
例:
int deleteUsers(List<Integer> ids);
<delete id="deleteUsers">
delete from userinfo where id in
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>
效果:
mybatis:
mapper-locations: classpath:mapper/**Mapper.xml
configuration: # 配置打印 MyBatis 执行的 SQL
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 配置打印 MyBatis 执行的 SQL
logging:
level:
com:
example:
mybatis3: debug
加上@Transactional注解:
可以加到类或者方法上
@SpringBootTest
@Transactional
class UserinfoMapperTest {
@Autowired
private UserinfoMapper userinfoMapper;
@Test
void deleteUser() {
int i = userinfoMapper.deleteUser(2);
System.out.println(i);
Assertions.assertEquals(1,i);
}
}
效果: