gpt4 book ai didi

java - MyBatis @Select 引用映射器 XML 文件中定义的选择

转载 作者:行者123 更新时间:2023-11-30 09:39:22 30 4
gpt4 key购买 nike

我在 mapper.xml 文件中定义了一个选择:

<mapper namespace="foo">

<select id="selectWithRoles" parameterType="String" resultMap="personWithRoles">
select *
from
PERSON P
left outer join PERSON_ROLE R on P.ID = R.PERSON_ID
where P.ID = #{id}
</select>

<resultMap id="personWithRoles" type="Person">
<id property="id" column="ID" />
<collection property="roles" ofType="Role">
<id property="personId" column="PERSON_ID"/>
<result property="name" column="NAME"/>
</collection>
</resultMap>

</mapper>

我想通过注释通过 DAO 接口(interface)公开此选择,而不将选择语句复制到 DAO 中。以下工作正常:

@Select("select * from PERSON P left outer join PERSON_ROLE R on P.ID = R.PERSON_ID where P.ID = #{id}")
@ResultMap("personWithRoles")
public Person loadByIdWithRoles(String id);

但我不喜欢将 SQL 复制到注释中(可能很长)想要这样的东西:

@Select("selectWithRoles")
public Person loadByIdWithRoles(String id);

其中“selectWithRoles”是在 XML 中定义的选择的 ID。可能吗?

最佳答案

找到答案。以防万一有人需要它:显然只要 XML 文件中的 namespace 与接口(interface)的完全限定名称匹配并且方法名称与 XML 中的 id 匹配,那么 MyBatis 将神奇地使其在没有注释的情况下工作。

<mapper namespace="foo">

<select id="selectWithRoles" parameterType="String" resultMap="personWithRoles">
select *
from
PERSON P
left outer join PERSON_ROLE R on P.ID = R.PERSON_ID
where P.ID = #{id}
</select>

<resultMap id="personWithRoles" type="Person">
<id property="id" column="ID" />
<collection property="roles" ofType="Role">
<id property="personId" column="PERSON_ID"/>
<result property="name" column="NAME"/>
</collection>
</resultMap>

</mapper>

请注意,包名称与 XML 中的命名空间匹配,方法名称与 select id 匹配:

package foo;
public Person public Person selectWithRoles(String id);

关于java - MyBatis @Select 引用映射器 XML 文件中定义的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9856657/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com