is it possible to map a list of java.time.Month to a seperate Table like so:
|MyEntity | |MyEntity_Month | |Month |
|---------------------| |------------------| |---------------|
|id : long | |myEntity_Id : long| |id : long |
| |----|month_Id : long |----| |
|---------------------| |------------------| |---------------|
I have tried it like this but it that only creates a table MyEntity_Month with a myEntity_Id and values:
@ElementCollection(targetClass = Month.class, fetch = FetchType.EAGER)
@Enumerated(EnumType.STRING)
@CollectionTable(name = "MyEntity_Months"
, joinColumns = @JoinColumn(name = "myEntity_id"))
private List<Month> months;
The problem with that solution is that the values are repeated for each MyEntity instead of associated. Database view of the above annotation configuration:
|MyEntity | |MyEntity_Month |
|---------------------| |-----------------------|
|id : long | |myEntity_id | MONTH |
|... |----|-----------------------|
|---------------------| |1 | NOVEMBER |
|1 | DECEMBER |
|2 | JANUARY |
|2 | DECEMBER |
|-----------------------|
Is it possible to map via assocation table so that I need only 12 Month Strings in the database? I'm using Hibernate 4.3 / JPA 2.1 btw
The type java.time.Month does not have @Entity annotations, so this is not recognized as an entity by hibernate. You can achieve your desired table mapping if you introduce something like a 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;
}
Then if you run this through hibernate with a create-drop
hbm2ddl.auto
property, then you get the following tables:
Hibernate: create table MonthWrapper (id bigint not null, month varchar(255), primary key (id))
Hibernate: create table MyEntity (id bigint not null, primary key (id))
Hibernate: create table MyEntity_MonthWrapper (MyEntity_id bigint not null, months_id bigint not null)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.