是否可以将java.time.Month列表映射到单独的表中,如下所示:
|MyEntity | |MyEntity_Month | |Month |
|---------------------| |------------------| |---------------|
|id : long | |myEntity_Id : long| |id : long |
| |----|month_Id : long |----| |
|---------------------| |------------------| |---------------|
我已经尝试过这样但它只创建了一个带有myEntity_Id和值的表MyEntity_Month:
@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
答案 0 :(得分:1)
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;
}
然后,如果您通过hibernate使用create-drop
hbm2ddl.auto
属性运行此操作,那么您将获得以下表格:
Hibernate:创建表MonthWrapper(id bigint not null,month varchar(255),primary key(id))
Hibernate:创建表MyEntity(id bigint not null,主键(id))
Hibernate:创建表MyEntity_MonthWrapper(MyEntity_id bigint not null,months_id bigint not null)