Say I have this class:
@Entity
@Table(name="PICTURE")
public class Picture{
private String category1, category2;
}
but the database structure looks like this:
TABLE PICTURE {
int category1;
int category2;
...
}
TABLE PICTURE_REF {
int category;
String categoryName;
...
}
How would I use JPA annotations on Picture so that any time I request an instance of it, category1 and category2 contains the categoryName from the PICTURE_REF table instead of the actual integer id stored in the PICTURE table?
I’m also wondering how saves would work because the user would select a category from a dropdown and the corresponding category integer ID would be what’s stored in the PICTURE table.
From your description ,
PICTURE.category1andPICTURE.category2have the many-to-one relationship to thePICTURE_REFThe following shows the bi-directional mapping between them using annotation:
For table PICTURE:
For table PICTURE_REF:
Important Points:
@Entitymarks the java class as an hibernate entity. It is mapped to the name of the table specified in the@TableUse
@ManyToOneto define the many-to-one relationshipIn the relational database , many-to-one relationship is expressed by using the following foreign key constraint:
“Many side table” has a FK column which only accepts the PK of the “one side table”.
In your case , these FK columns are
PICTURE.category1andPICTURE.category2. The name of these FK columns can be explicitly defined by thenameattribute of@JoinColumn.FetchType.EAGERmakes thatPictureRefwill be eagerly fetched wheneverPictureis loaded or getDepending on your requirement , you can do the
unidirectionalmapping by omitting@OneToManyin thePictureRef.It will also work .But givenPictureRef, you cannot access its PictureGiven a Picture instance , you can get its categoryName and categoryId by