我有以下表格:
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
);
我想选择用户和他的所有朋友,所以我做了Map
<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>
我试过运行select-它运行起来没有任何问题。问题出现在resultmap中
如果我插入不带 <collection>
标记,一切正常,Map程序返回我的用户对象
<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>
Map器调用的结果为空。我在控制台中没有看到任何错误。如何将用户的所有好友加载到该用户中?
p、 还有,有趣的是,我在日志中看到了下面的文本
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
据我所知,select正常工作,但是当mybatis构建对象时,出现了一些问题。
1条答案
按热度按时间c8ib6hqw1#
解决方法很简单:我已经给这个列添加了别名,一切都开始顺利
另外,如果没有至少一个属性Map到类,那么结果将是空值