MyBatis:如何从查询中存储多个值?

MyBatis: How do I store Multiple Values from Query?

在我的 AppMapper.xml 中,我有一个查询:

<select id="getCompleteDetails" parameterType="Map" resultType="String">
  SELECT * FROM PersonProfile WHERE ID = #{id}
</select>

假设它要 return 姓名、地址、年龄、职业,这些都是字符串。 我用这个对吗?

<select id="selectPerson" parameterType="int" resultType="String">

或者因为要接收多个值,所以应该类似​​于

<select id="selectPerson" parameterType="int" resultMap="PersonProfileObj">

如果我使用 "resultMap=PersonProfileObj",我知道我需要创建像

这样的 resultMap
<resultMap type="com.test.PersonProfileObj" id="PersonProfileObj">
 <result property="Name" column="Name">
<result property="Address" column="Address">
<result property="Age" column="Age">
<result property="Profession" column="Profession">
</resultMap>

//我的resultMap正确吗?

*我在问是用resultType=String还是resultMap"PersonProfileObj"

我的理解正确吗?

resultType 指定由给定映射 SQL 编辑的对象(如果多个对象被 returned,则为列表的元素)的类型] 陈述。如果您指定 resultType="String",则查询应该 return 正好是一个字符串类型的字段。

如果您需要 return 多个字段,您可以:

  1. 创建对象并将这些字段映射到对象属性。
  2. return一张地图。在这种情况下,行中的每个字段都将是映射中的一个条目,键等于列名,值等于字段值。

当您 return 一个对象时,您可以使用默认映射来设置与列名称相对应的对象属性,或者您可以指定 resultMap 允许在中设置 column -> property 映射更灵活的方式。

另请注意,resultMap 上有一个 autoMapping 属性,它将列隐式映射到具有相同名称的属性,因此在您的示例中,假设列与属性具有相同的名称就足够了要有这个映射:

<resultMap type="com.test.PersonProfileObj" id="PersonProfileObj" autoMapping="true">
</resultMap>

另请注意,您通常希望为结果映射指定 id,尤其是在 collections/associations 映射中使用查询或具有连接时。