实体类中的变量与数据库对应表的变量名不一致,如果sql 中没有添加别名, 那么会找不到对应的字段, 则会报空指针异常。如果实体类和数据库字段一样则不需要加As
User
@Data
@TableName(value = "richfit_myku")
public class User implements Serializable {
private int userid;
private String username;
private int usersex;
private Double degree;
}
UserInfo
@Data
@TableName(value = "richfit_mykuinfo")
public class UserInfo implements Serializable {
private int id;
private String hobby;
private int userid;
}
第一种方式 as
<select id="queryUserTest" resultType="com.mybatis.api.mybatis.model.UserAndUserInfoResult">
select b.id,b.my_hobby as hobby,a.user_id as userid,a.user_sex as sex from richfit_myku a,richfit_mykuinfo b
where 1=1
<if test="username !=null and username !=''">
and a.user_name=#{username}
</if>
<if test="hobby !=null and hobby !=''">
and b.my_hobby=#{hobby}
</if>
and a.user_id=b.user_id
</select>
第二种方式 resultMap
<resultMap type="com.mybatis.api.mybatis.model.UserInfo" id="UserInfoMap">
<id column="id" property="id"/>
<result column="my_hobby" property="hobby"/>
<result column="user_id" property="userid"/>
</resultMap>
<resultMap type="com.mybatis.api.mybatis.model.User" id="UserMap">
<id column="user_id" property="userid"/>
<result column="user_name" property="username"/>
<result column="user_sex" property="user_sex"/>
<result column="degree" property="degree"/>
</resultMap>
<select id="queryUserTest" resultMap="UserInfoMap,UserMap">
select b.id,b.my_hobby,a.user_id,a.user_sex from richfit_myku a,richfit_mykuinfo b
where 1=1
<if test="username !=null and username !=''">
and a.user_name=#{username}
</if>
<if test="hobby !=null and hobby !=''">
and b.my_hobby=#{hobby}
</if>
and a.user_id=b.user_id
</select>
第三种方式 mapUnderscoreToCamelCase
使用这种配置方式不需要手动指定别名 MyBatis 字段按照 “下画线转驼峰”的方式 自动映射。
首先了解:
printEmployeePaychecks();骆驼式命名法——函数名中的每一个逻辑断点都有一个大写字母来标记
print_employee_paychecks();下划线法-—函数名中的每一个逻辑断点都有一个下划线来标记。
springboot配置:
sql:
select role name , enabled, create by, create me from sys role
where id = #{id)