mybatis
mybatis中实体类属性名需要和mysql中表字段名完全一样,才能完成映射,比如select * from user where id=1 返回一行,经过mybatis转化为实体类User。如果某个属性对应不上,则返回的实体类对象该属性为空。解决名称不一致:
- 如果mysql定义表时严格按下划线格式,实体类中按驼峰规则,(这也是mysql和java中的习惯命名),可以在application.properties中配置
mapUnderscoreToCamelCase=true
- 在mapper.xml中用resultMap自定义映射
<!--
resultMap标签:设置自定义映射
属性:
id属性:表示自定义映射的唯一标识
type属性:查询的数据要映射的实体类的类型
子标签:
id标签:设置主键的映射关系
result标签:设置普通字段的映射关系
association标签:设置多对一的映射关系
collection标签:设置一对多的映射关系
属性:
property属性:设置映射关系中实体类中的属性名
column属性:设置映射关系中表中的字段名
-->
<mapper namespace="com.example.mappper.UserMapper">
<resultMap id="UserMap" type="com.example.dao.pojo.User">
<id property="id" column="id"/>
<result property="empName" column="emp_name"/>
<result property="age" column="age"/>
</resultMap>
<select id="selectById" resultType="UserMap">
select * from user where id = #{id}
</select>
</mapper>
mybatis-plus
默认情况,如果mysql表按下划线格式,实体类中属性按驼峰规则,mybatis-plus可以自动映射。
如果表列名已经和体类中属性名一致,可以在application.properties中配置取消自动转换:
mybatis-plus.configuration.map-underscore-to-camel-case=false
- 使用注解
@Data
public class UserInfo {
@TableId(value = "uuid")
private Integer id;
@TableField(value = "uname")
private String userName;
@TableField(value = "pword")
private String passWord;
}
- 在mapper.xml中用resultMap
和mybatis一样