I've got two tables in my database that look like this, with a foreign key from job_label.job_id
to equivalent column in job_record
. Additionally, the triple of job_id
, label_key
, and label
in job_record
has a unique constraint.
mysql> select * from job_record;
+--------+---------+
| job_id | state |
+--------+---------+
| 1 | success |
| 2 | running |
| 3 | errored |
| 4 | success |
+--------+---------+
mysql> select * from job_label
+--------+-----------+--------+
| job_id | label_key | label |
+--------+-----------+--------+
| 1 | name | job 1 |
| 1 | type | normal |
+--------+-----------+--------+
On the Java class side I have this class:
@Entity
@Table(name = "job_record")
public class JobRecord {
@Id
@Column(name = "job_id")
private String jobId;
@Enumerated(EnumType.STRING)
@Column(name = "state")
private JobState state;
}
I've tried to define a class for job_label
that looks something like this:
public class JobLabelRecord {
@Enumerated(EnumType.STRING)
@Column(name = "label_key")
private JobLabelKey key;
@Column(name = "label")
private String label;
}
And then I want a field in JobRecord
that provides me all labels for that Job as a List<JobLabelRecord>
. However, nothing I've tried works.
I've tried declaring JobLabelRecord
as Embeddable
with the equivalent field in JobRecord
as Embedded
. I've tried using ManyToOne
and OneToMany
mappings, but that fails because there's no Id
columns in JobLabelRecord
(and nothing I do with those works correctly).
Am I supposed to be using an ElementCollection
here instead? I've tried that as well, but without success.
Any ideas here? Thanks!
You can find a simple example for this by searching for "jpa elementcollection separate table", such as JPA Tutorial - JPA ElementCollection CollectionTable Override Example . Applying this example to your problem gives the following:
@Entity
@Table(name = "job_record")
public class JobRecord {
@Id
@Column(name = "job_id")
private Integer jobId;
@Enumerated(EnumType.STRING)
@Column(name = "state")
private JobState state;
@ElementCollection
@CollectionTable(name="job_label",
joinColumns=@JoinColumn(name="job_id"))
private List<JobLabelRecord> labels;
...
@Embeddable
public class JobLabelRecord {
@Enumerated(EnumType.STRING)
@Column(name = "label_key")
private JobLabelKey key;
@Column(name = "label")
private String label;
...
Note also the JobRecord
id should probably be an Integer
.
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.