簡體   English   中英

如何使用mybatis將具有2個集合的對象插入數據庫

[英]How to insert object with 2 collections into DB using mybatis

到目前為止,我的對象User具有許多角色。 當我將其插入數據庫時​​,我

<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
);

該代碼適用於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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM