使用 Hibernate 在 Postgresql 中持久化 EnumSet
Persisting EnumSet in Postgresql with Hibernate
Effective Java, Item 32, states Use EnumSet instead of bit fields. I also found this nice tutorial on the topic. This book has been around for a while, so why don't I find any posts on how to persist an EnumSet with Hibernate? Well, I actually found this one, and another one,但它们都很旧,指向相同且更旧的解决方案,不幸的是这对我没有帮助,也许是因为我缺乏更深入的休眠知识?这是我的代码摘要:
public class MyThing {
public enum MyOptions {
FLAG1, FLAG2
}
@Id
private Long id;
@Column(name = "options")
private EnumSet<MyOptions> options;
// [other fields, getters, setters etc]
}
我尝试过其他注释,例如
@ElementCollection
有无(targetClass = MyOptions.class)
和
@JoinTable(name = "my_options",
joinColumns = @JoinColumn(name = "id"))
还有
@OneToMany
@JoinColumn(name = "options")
但运气不好。
我最好将信息存储在 my_thing
table 的新列中,但如果需要,我也可以使用单独的 table 作为枚举。
试试这个
@ElementCollection
@CollectionTable(name = "my_options",
joinColumns = @JoinColumn( name = "mything_id"))
@Column(name = "option")
@Enumerated(EnumType.STRING)
private Set<MyOptions> options;
使用此配置,您需要一个名为 my_options
的数据库 table,其中包含列 option
和 mything_id
,目标 MyThing
table。
Effective Java, Item 32, states Use EnumSet instead of bit fields. I also found this nice tutorial on the topic. This book has been around for a while, so why don't I find any posts on how to persist an EnumSet with Hibernate? Well, I actually found this one, and another one,但它们都很旧,指向相同且更旧的解决方案,不幸的是这对我没有帮助,也许是因为我缺乏更深入的休眠知识?这是我的代码摘要:
public class MyThing {
public enum MyOptions {
FLAG1, FLAG2
}
@Id
private Long id;
@Column(name = "options")
private EnumSet<MyOptions> options;
// [other fields, getters, setters etc]
}
我尝试过其他注释,例如
@ElementCollection
有无(targetClass = MyOptions.class)
和
@JoinTable(name = "my_options",
joinColumns = @JoinColumn(name = "id"))
还有
@OneToMany
@JoinColumn(name = "options")
但运气不好。
我最好将信息存储在 my_thing
table 的新列中,但如果需要,我也可以使用单独的 table 作为枚举。
试试这个
@ElementCollection
@CollectionTable(name = "my_options",
joinColumns = @JoinColumn( name = "mything_id"))
@Column(name = "option")
@Enumerated(EnumType.STRING)
private Set<MyOptions> options;
使用此配置,您需要一个名为 my_options
的数据库 table,其中包含列 option
和 mything_id
,目标 MyThing
table。