1、parameterType 配置参数
在mybatis的crud中 SQL 语句传参,使用标签的 parameterType 属性来设定。该属性的取值可以是基本类型,引用类型(例如:String 类型),还可以是实体类类型(POJO 类)。同时也可以使用实体类的包装类,下面介绍如何使用实体类的包装类作为参数传递。
查询条件实体类
@Data
public class QueryVo {
private User user;
}
dao接口类
//根据查询封装类查询用户
List<User> selectByVo(QueryVo vo);
映射文件
<select id="selectByVo" parameterType="com.wjh.domain.QueryVo" resultType="com.wjh.domain.User">
select * from user where username like #{user.username} and sex = #{user.sex}
</select>
测试
//根据查询封装类查询用户
@Test
public void testSelectByQueryVo(){
QueryVo queryVo = new QueryVo();
User user = new User();
user.setUsername("%王%");
user.setSex('女');
queryVo.setUser(user);
List<User> users = userDao.selectByVo(queryVo);
for (User user1 : users){
System.out.println(user);
}
}
测试结果:
2、Mybatis 的输出结果封装
1、resultType 配置结果类型
在开发中实体类属性的命名规范一般为驼峰命名。
user实体类:
@Data
public class User {
private Integer id;
private String userName;
private Date userBirthday;
private char userSex;
private String userAddress;
}
数据库列名:
当测试查询所有用户时,查询结果为:
分析:只有userName有数据,其他属性为null,因为数据库列名和实体类属性名不一致而导致查询结果封装不进去。而mysql字段不区分大小写,所有userName可以把数据封装进去。
解决方法:
- 查询语句起别名:
<select id="getAllUser" resultType="com.wjh.domain.User">
select id ,username,birthday as userBirthday,sex as userSex,address as userAddress from user
</select>
2、定义 resultMap
在userDao.xml中定义resultMap
<!--对应的dao接口-->
<mapper namespace="com.wjh.dao.UserDao">
<!--定义resultMap,配置查询结果列名和实体类属性名的对应关系-->
<resultMap id="userResultMap" type="com.wjh.domain.User">
<!--主键字段的对应-->
<id column="id" property="id"></id>
<result column="username" property="userName"></result>
<result column="birthday" property="userBirthday"></result>
<result column="sex" property="userSex"></result>
<result column="address" property="userAddress"></result>
</resultMap>
<!--id的值必须是对应的方法名-->
<select id="getAllUser" resultMap="userResultMap">
<!--select id ,username,birthday as userBirthday,sex as userSex,address as userAddress from user-->
select * from user
</select>
</mapper>
查询结果: