[英]How to insert object with 2 collections into DB using mybatis
Until now I had object User with many Roles. 到目前为止,我的对象User具有许多角色。 When I was inserting it into DB, I
当我将其插入数据库时,我
<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 looks like this: 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>
All of this was working perfectly....until I decided to add List to user. 所有这一切都工作正常。...直到我决定将List添加到用户。 Now I have no clue how to insert this object into DB (PGSQL) using mybatis.
现在我不知道如何使用mybatis将对象插入DB(PGSQL)。
My User object looks like this: 我的用户对象如下所示:
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;
...
}
I Did try to wrap current insert into another with as, but it was not working. 我没有尝试用as将当前插入内容包装到另一个插入中,但是没有用。 My other tries are not even worth mentioning
我的其他尝试甚至都不值得一提
Table for object RemovedPermission is: 对象RemovedPermission的表为:
CREATE TABLE user_removed_permission
(
user_id INT NOT NULL,
permission_id INT NOT NULL,
expiration_time TIMESTAMP DEFAULT NULL
);
This code works for PostrgeSQL 10.4 and MyBatis 3.4.6 该代码适用于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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.