到目前为止,我的对象用户有很多角色。当我将它插入数据库时,我
<sql id="insertUserWithRoles">
WITH inserted_user as (
<include refid="insertUserWithoutRoles"/>
RETURNING id)
insert into user_role values
<foreach collection="user.authorities" index="index" item="role">
<if test="index != 0">
,
</if>
((select id from inserted_user), (select id from role where role = #{role.role}))
</foreach>
</sql>
insertUserWithoutRoles看起来像这样:
<sql id="insertUserWithoutRoles">
INSERT INTO "user" (username, password, account_non_expired, account_non_locked, credentials_non_expired, enabled)
VALUES (#{user.username}, #{user.password},#{user.accountNonExpired},#{user.accountNonLocked},#{user.accountNonLocked}, #{user.enabled})
</sql>
所有这一切都完美无缺......直到我决定向用户添加List。现在我不知道如何使用mybatis将此对象插入到DB(PGSQL)中。
我的用户对象如下所示:
public class User implements UserDetails, CredentialsContainer {
@Nullable
private Integer id;
private String username;
private String password;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
private boolean enabled;
private Set<BoostmeRole> authorities;
private List<RemovedPermission> removedPermissions;
...
}
我尝试用as包装当前插入到另一个插件,但它没有工作。我的其他尝试甚至都不值得一提
对象RemovedPermission的表是:
CREATE TABLE user_removed_permission
(
user_id INT NOT NULL,
permission_id INT NOT NULL,
expiration_time TIMESTAMP DEFAULT NULL
);
答案 0 :(得分:0)
此代码适用于PostrgeSQL 10.4和MyBatis 3.4.6
<insert id="create" parameterType="User">
<selectKey keyProperty="id" keyColumn="id" resultType="int" order="BEFORE">
SELECT nextval('users_id_seq');
</selectKey>
INSERT INTO users(id, name, password)
VALUES (#{id}, #{name}, #{password});
INSERT INTO users_roles(user_id, role_id) VALUES
<foreach collection="roles" item="role" separator=",">
(#{id}, (SELECT r.id FROM roles r WHERE r.name = #{role.name}))
</foreach>;
</insert>