I have a static table with two columns: statusCode, statusName. This table will hold only 7 records. And a table Candidate with OneToOne relation with Status .
It looks more or less like this:
@Entity
public class Status {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String statusName;
String statusCode;
// getters and setters
}
And
@Entity
public class Candidate {
// properties, getters and setters
@OneToOne
Status status;
}
The problem is that every time I create a new Candidate I also need to create a new record in my Status table and in this way I will store lots of redundant data (there are only 7 possible states). I just want to set the id for status in the Candidate entity and later to be able to receive status details and in this way avoiding creating unnecessary records in Status table.
Thanks
First You should change OneToOne to ManyToOne
@Entity
public class Candidate{
// properties, getters and setters
@ManyToOne
Status status;
}
And when creating a new Candidate to have to fetch the Status and assigne it.
Either with
Status status = em.find(Status.class, id);
That will load the whole Status or if you only want to set the foreign key and don't need the Status object
Status status = em.getReference(Status.class, id);
Then you can assigned the retrieved Status to the candidate.
em is the EntityManager
You should be able to do something similar to the following:
In Candidate:
@ManyToOne
@JoinColumn(name="STATUS_ID")
Status status;
In Status:
@OneToMany(mappedBy="status")
private List<Candidate> candidates;
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.