My MyBatis select is
// result map that sub-selects a folder
<resultMap id="beanWithFolderMap" type="com.example.BeanWithFolder">
<id column .../>
<association column="folder_id" property="folder" javaType="com.example.Folder" select="selectFolder"/>
</resultMap>
// folder sub-select
<select id="selectFolder" resultType="com.example.Folder">
SELECT
folder_id
name,
FROM folders
WHERE folder_id=#{folderId}
</select>
如果找不到匹配folder_id的行,我想返回一个特殊的Folder类实例。
现在MyBatis在找不到行时返回null。我想返回一个设置了folderId字段的Folder实例 - 因为我知道我在寻找什么,我至少可以设置这个字段。
怎么做?
类似
SELECT
#{folderId} as folder_id,
name,
FROM folders
WHERE folder_id=#{folderId}
会很棒,但我得到异常“无法确定参数$ 1的数据类型”
答案 0 :(得分:1)
如果频繁使用此查询,我会为它创建一个小函数。这可能是最快的:
CREATE OR REPLACE FUNCTION f_foo(_folder_id int)
RETURNS TABLE (folder_id int, name text) AS
$func$
BEGIN
RETURN QUERY
SELECT f.folder_id, f.name
FROM folders f
WHERE f.folder_id = $1;
IF NOT FOUND THEN -- only if nothing was found
RETURN QUERY
VALUES ($1, NULL); -- columns must match!
END IF;
END
$func$ LANGUAGE plpgsql STABLE;
呼叫:
SELECT * FROM f_foo(133)
您在脚本中使用的内容。就像从桌子上选择一样。
使用纯SQL还有其他方法,最好使用NOT EXISTS
。我想CTE会有所帮助:
WITH x AS (
SELECT folder_id, name
FROM folders
WHERE folder_id = $1;
)
SELECT * FROM x
UNION ALL
SELECT $1, NULL
WHERE NOT EXISTS (SELECT 1 FROM x);