我有以下表格:
CREATE TABLE users (
id VARCHAR (255) NOT NULL,
name VARCHAR (255) NOT NULL,
create_date TIMESTAMP NOT NULL,
email VARCHAR (255) NOT NULL,
password VARCHAR (255) NOT NULL,
last_visit TIMESTAMP,
avatar_id VARCHAR (255)
);
CREATE TABLE user_friends (
user_id VARCHAR (255) NOT NULL,
friend_id VARCHAR (255) NOT NULL
);
CREATE TABLE file (
id VARCHAR (255) NOT NULL,
file_path VARCHAR (255) NOT NULL,
create_date TIMESTAMP NOT NULL,
user_id VARCHAR (255) NOT NULL
);
我想与所有朋友一起选择用户,所以我已经制作了mapper
<sql id="coreUserAttributes">
users.id,
users.name,
users.last_visit as lastVisit
</sql>
<select id="getUser" resultMap="UserRM">
SELECT
<include refid="coreUserAttributes"/>,
f.id as friendId,
f.name as friendName
FROM users
LEFT JOIN user_friends ON users.id = user_friends.user_id
LEFT JOIN users f ON f.id = user_friends.friend_id
<where>
users.id = #{id}
</where>
</select>
我尝试过选择 - 它没有任何问题。 问题出在ResultMap
中如果我插入没有<collection>
标签的resultMap,一切都运行良好
和mapper返回我的User对象
<resultMap id="UserRM" type="User">
<id column="id"/>
</resultMap>
但是当我插入<collection>
标签
<resultMap id="UserRM" type="User">
<id column="id"/>
<collection property="friends" ofType="User" javaType="ArrayList">
<id column="friendId"/>
<result column="friendName" property="name"/>
</collection>
</resultMap>
映射器调用的结果为null。我在控制台中看不到任何错误。 如何向所有朋友加载用户?
P.S 另外,有趣的是,我在日志中看到以下文字
2017-01-03 22:29:19 DEBUG u.s.network.query.UserMapper.getUser - ==> Preparing: SELECT users.id, users.name, users.last_visit as lastVisit , f.id as friendId, f.name as friendName FROM users LEFT JOIN user_friends ON users.id = user_friends.user_id LEFT JOIN users f ON f.id = user_friends.friend_id WHERE users.id = ?
2017-01-03 22:29:19 DEBUG u.s.network.query.UserMapper.getUser - ==> Preparing: SELECT users.id, users.name, users.last_visit as lastVisit , f.id as friendId, f.name as friendName FROM users LEFT JOIN user_friends ON users.id = user_friends.user_id LEFT JOIN users f ON f.id = user_friends.friend_id WHERE users.id = ?
2017-01-03 22:29:19 DEBUG u.s.network.query.UserMapper.getUser - ==> Parameters: 1(String)
2017-01-03 22:29:19 DEBUG u.s.network.query.UserMapper.getUser - ==> Parameters: 1(String)
2017-01-03 22:29:19 DEBUG u.s.network.query.UserMapper.getUser - <== Total: 1
2017-01-03 22:29:19 DEBUG u.s.network.query.UserMapper.getUser - <== Total: 1
据我所知,选择正常,但是当mybatis构建对象时,会出现一些问题。
答案 0 :(得分:0)
解决方案非常简单:我已经为这些列添加了别名,一切都开始运作
<sql id="coreUserAttributes">
users.id AS id,
users.name AS name,
users.last_visit as lastVisit
</sql>
此外,如果没有至少一个属性要映射到您的类 - 结果将为空值