7

我想将一组选项表示为我的实体中的 EnumSet 和我的数据库中的一对多关系。这是如何正确完成的?我只能找到旧的(预注释)答案或不使用两个表格的答案。

我定义了以下表格:

CREATE TABLE Users (
    id                      SERIAL PRIMARY KEY,
    name                    VARCHAR(255) NOT NULL UNIQUE
);

CREATE TABLE User_Options (
    user_id                 INT,
    user_option             VARCHAR(255),
    PRIMARY KEY (user_id, user_option),
    FOREIGN KEY (user_id) REFERENCES Users(id)
                ON DELETE CASCADE
                ON UPDATE CASCADE
);

这个实体类:

@Entity(name = "Users")
public final class User {

    @Id
    @GeneratedValue
    private int id;

    @Column(nullable = false, unique = true)
    private String name;

    private final Set<UserOption> options;

    {
        this.options = EnumSet.noneOf(UserOption.class);
    }

    /* plain getter for id included */

    /* plain getter and setter for name included */

    @ElementCollection(fetch = FetchType.EAGER)
    @Enumerated(EnumType.STRING)
    @CollectionTable(name = "User_Options"
            , joinColumns = @JoinColumn(name = "user_id"))
    @Column(name = "user_option", nullable = false)
    public Set<UserOption> getOptions() {
        return this.options;
    }

}

当然还有一个枚举:

public enum UserOption {

    OPTION_A,
    OPTION_B,
    OPTION_C;

}

当我启动 Tomcat 时,出现以下异常:

org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: Users, for columns: [org.hibernate.mapping.Column(options)]

这个异常是一堆相互导致的异常的根源。它会导致javax.persistence.PersistenceException(无法构建EntityManagerFactory),进而导致一些依赖注入异常。

我承认我对 JPA/Hibernate 不够精通,无法理解我做错了什么。有人可以帮帮我吗?

4

1 回答 1

7

事实证明,答案比我想象的要简单。您不能在实例变量和 getter 上混合使用 JPA 注释。注释本身很好。我按如下方式更改了我的实体类,现在一切正常。

@Entity(name = "Users")
public final class User {

    @Id
    @GeneratedValue
    private int id;

    @Column(nullable = false, unique = true)
    private String name;

    @ElementCollection(fetch = FetchType.EAGER)
    @Enumerated(EnumType.STRING)
    @CollectionTable(name = "User_Options"
            , joinColumns = @JoinColumn(name = "user_id"))
    @Column(name = "user_option", nullable = false)
    private final Set<UserOption> options;

    {
        this.options = EnumSet.noneOf(UserOption.class);
    }

    /* plain getter for id included */

    /* plain getter and setter for name included */

    public Set<UserOption> getOptions() {
        return this.options;
    }

}
于 2013-02-12T11:46:28.927 回答