在Mybatis中,解决数据库字段名与java实体类属性名不一致的三种方式

在使用Mybatis来持久化数据库时,有时候会碰到数据库中表中的字段与java实体类中属性名不一致的情况,在这种情况下Mybatis是不能完成字段的自动映射的。而通常情况下,数据库及实体类是不应该被改的的。所以要在不改变数据库以及实体类的情况下解决这个问题,下面是解决该问题的三种方式:

java实体类:

public class User
{
	private Long id;
	private String userName;
	private String passWord;
	/**
	 * ...
	 * get,set方法不再列出
	 * ...
	 * */
}


1.既然是因为名字不一致而导致Mybatis不能完成自动映射,那么就可以将两者的名字想办法保持一致,为查询出的数据库字段起个别名就可以,实例如下:

<select id="selectUserById" resultType="User">
        select 
        id,
        user_name as userName,<!--不用在意大小写,Mybatis会先转换成大写再进行匹配  -->
        user_password as userPassword,
        from user
        where id = #{id}
</select>
2.另一种解决名字不一致的方式是事先指定映射关系,这样Mybatis也能自动完成映射。Mybatis提供了resultMap可以指定映射关系,示例如下:

<resultMap type="User" id="UserResultMap">
		<id column="id" property="id"/>
		<result column="user_name" property="userName"/>
		<result column="user_password" property="userPassword"/>
</resultMap>
	
	
<select id="selectUserById" resultMap="UserResultMap">
        select 
        id,
        user_name,
        user_password,
        from user
        where id = #{id}
</select>
注意:

1.使用resultMap时,在select语句配置中,要有resultMap替换原来的resultType。

2.resultMap中的column要与查询到的字段名一致,property要与实体类的属性一致。

3.在通常情况下,java中的实体类中的属性一般是采用驼峰命名命名的,而数据库中表的字段则用下划线区分字母。在这种情况下,Mybatis提供了一个全局属性mapUnderscoreToCamelCase来解决两者名字不一致的问题。

<settings>
	<!--其他配置...  -->
	<setting name="mapUnderscoreToCamelCase" value="true"/>
	<!--其他配置...  -->
</settings>
注意:因为该属性是全局属性,所以需要配置在Mybatis的配置文件中,而不是Mapper.xml映射文件中。


猜你喜欢

转载自blog.csdn.net/li627528647/article/details/77915661