JPA応用編:列挙型とN:Nで紐付ける

以下の3点を通常のカラムのアノテーションの他に追加する必要がある。
@CollectionTableを使って関連テーブルとカラムを指定する。
@Enumeratedで永続化フィールドを列挙型として指定する。
@ElementCollectionでEntityではないクラスも使用できるようにする。

@Entity
@Table(name = "app_user")
public class User implements Serializable {

    /** 権限 */
    @Column(nullable = false)
    @CollectionTable(name = "app_user_roles", joinColumns = @JoinColumn(name = "username"))
    @Enumerated(EnumType.STRING)
    @ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
    private List<Role> roles;
/**
 * 権限
 */
public enum Role implements Serializable {

    /** 管理者 */
    ROLE_ADMIN,

    /** 一般 */
    ROLE_USER;
}
create table app_user (
    username varchar(16) not null,
    primary key (username)
);

create table app_user_roles (
    username varchar(16) not null,
    roles varchar(16) not null,
    primary key (username, roles)
);

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください