[Mybatis] resultType and resultMap

1. resultType: Indicates what type to encapsulate the data into


for example:

<select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee">
	select * from tbl_employee where id = #{id}
</select>

Indicates that the queried data is encapsulated into the Employee entity type and returned to the getEmpById method

Fields in the tbl_employee table



Properties in Employee entity



It can be seen that the last_name in the database does not correspond to the lastName in the entity, so the lastName in the queried data is null

At this time, you need to turn on the camel case nomenclature:

<settings>
	<setting name="mapUnderscoreToCamelCase" value="true"/>		
</settings>

After the camel case naming method is turned on, the last_name in the database and the lastName in the entity can correspond.


2.resultMap: custom result set mapping rules (customize the encapsulation rules of a javaBean)

<!-- Customize the encapsulation rules of a javaBean
	type: the java type of the custom rule
	id: unique id for easy reference -->
	<resultMap type="com.atguigu.mybatis.bean.Employee" id="MySimpleEmp">
		<!-- Specify the encapsulation rules of the primary key column, because the encapsulation rules have been defined, you can turn off the camel case nomenclature
		id defines the primary key, the bottom layer will be optimized
		column: specify which column
		property: Specify the corresponding JavaBean property
		 -->
		<id column="id" property="id"/>
		<!-- Define common column encapsulation rules-->
		<result column="last_name" property="lastName"/>
		<!-- Other unspecified columns will be automatically encapsulated: we only need to write resultMap and write all the mapping rules -->
		<result column="email" property="email"/>
		<result column="gender" property="gender"/>
	
	</resultMap>


<!-- resultMap: custom result set mapping rules; -->
	<!-- public Employee getEmp·ById(Integer id); -->
	<select id="getEmpById" resultMap="MySimpleEmp">
		select * from tbl_employee where id=#{id}
	</select>

Because we have defined the encapsulation rules in resultMap, we can turn off the camel case.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325727733&siteId=291194637