是否可以像这样将java.time.Month列表映射到一个单独的Table:
|MyEntity | |MyEntity_Month | |Month |
|---------------------| |------------------| |---------------|
|id : long | |myEntity_Id : long| |id : long |
| |----|month_Id : long |----| |
|---------------------| |------------------| |---------------|
我已经尝试过这样做,但它只创建一个表MyEntity_Month与myEntity_Id和值:
@ElementCollection(targetClass = Month.class, fetch = FetchType.EAGER)
@Enumerated(EnumType.STRING)
@CollectionTable(name = "MyEntity_Months"
, joinColumns = @JoinColumn(name = "myEntity_id"))
private List<Month> months;
该解决方案的问题是每个MyEntity的值都是重复的,而不是相关联的。以上注释配置的数据库视图:
|MyEntity | |MyEntity_Month |
|---------------------| |-----------------------|
|id : long | |myEntity_id | MONTH |
|... |----|-----------------------|
|---------------------| |1 | NOVEMBER |
|1 | DECEMBER |
|2 | JANUARY |
|2 | DECEMBER |
|-----------------------|
是否有可能通过关联表映射,以便我只需要12个月的字符串在数据库中?我使用Hibernate 4.3/JPA 2.1 btw
类型java.time.Month没有@Entity注释,因此hibernate不会将其识别为实体。如果引入像MonthWrapper这样的东西,就可以实现所需的表映射:
@Entity
public class MyEntity {
@Id
private Long id;
@OneToMany(fetch = FetchType.EAGER)
private List<MonthWrapper> months;
}
@Entity
public class MonthWrapper {
@Id
private Long id;
@Enumerated(EnumType.STRING)
private Month month;
}
然后,如果您通过具有create-drop
hbm2ddl.auto
属性的hibernate运行此操作,那么您将得到以下表:
Hibernate:创建表MonthWrapper (id bigint not null, month varchar(255),主键(id))
Hibernate: create table MyEntity (id bigint not null,主键(id))
Hibernate: create table MyEntity_MonthWrapper (MyEntity_id bigint not null, months_id bigint not null)