我想在我的实体中将一组选项表示为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中不够精通,无法理解我做错了什么。有人可以帮帮我吗?
答案 0 :(得分:6)
事实证明答案比我想象的更简单。您不能在实例变量和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;
}
}