在代码编写过程中,避免不了与数据库打交道,而这最基本的就是如何把数据映射为实体类,下面介绍几种比较常用的映射方式。
一:xml文件编写映射规则

<!-- 通用查询映射结果 -->
<resultMap id="myMap" type="com.**.**.entity.User">
        <id column="id" property="id" />
        <result column="user_name" property="userName" />
        <result column="user_password" property="userPassword" />
        <result column="email" property="email" />
        <result column="user_age" property="userAge" />
        <result column="is_del" property="isDel" />
</resultMap>

<!-- 查询语句 -->
<select id="selectById" resultMap="myMap">
    select * from user where id = #{id}
</select>

这种映射形式一个resulMap绑定一个实体类,但是越往后开发,返回的数据这一个实体类不能满足的情况下,需要新建很多这种映射,这种形式显然不是很好的选择。

二:sql的 * 改编写成 A as B的形式

<select id="selectById" resultType="com.**.**.entity.User">
    select 
    a.id as id,
    a.user_name userName,
    a.user_password as userPassword,
    a.email as email,
    a.user_age as userAge,
    a.is_del as isDel 
    from user a 
    where a.id = #{id}
</select>

这种写法无需任何配置,而且按需获取,且映射关系一目了然。缺点是代码编写量大。

三:mybatis框架或mybatis-plus自带的驼峰命名法映射规则

这里先讲mybatis框架的,作为现在最常用的最多人使用的持久层框架,mybatis自带的驼峰名发法更是简便了开发过程。首先需要开启这项命名规则,最常用的方式是通过配置文件修改配置参数。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <properties>
        <property name="dialect" value="mysql"/>
    </properties>
    <!-- 全局参数 -->
    <settings>
        <!-- 使用驼峰命名法转换字段。 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

开启后,实体类的属性命名就要按照驼峰命名法的规则命名,如表字段为user_name,则对应的实体类属性名应为userName,必须要严格按照这种规则编写,否则返回的数据不会对该属性赋值。

mybatis-plus作为mybatis的增强工具,只强不弱,对命名规则的也是如此。如果我们像上面一样通过配置文件开启了驼峰命名法的映射规则,那使用mybatis-plus封装的方法时不需要做任何操作,也可以达到自己编写sql语句的效果。但如果没有开启,我们只需要在实体类的属性上添加@TableField注解,指定映射关系即可。需要注意的是这里的注解方式只适用mybatis-plus封装的方法上,如果自己编写的sql语句是不会生效的。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    @TableId(type = IdType.UUID)
    private String id;

    @TableField(value = "user_name")
    private String userName;

    @TableField(value = "user_password")
    private String userPassword;

    private String email;

    @TableField(value = "user_age")
    private Integer userAge;

    @TableLogic
    @TableField(value = "is_del")
    private Integer isDel;
}
Logo

一站式 AI 云服务平台

更多推荐