How do I map a table to another lookup table using JPA?
I have two tables:
1) Application (int appid, int statusid, String appname, String apppity with getter and Setter methods)
2) App_Status (int statusid, String statusDescription with setter and getter methods)
I want to map the App_Status table to App_Status so that I don't have to separately query the App_Status table to get the StatusDescription. One thing I have to observe is that no matter what (Insert, update or delete) in the application table, the App_Status table should not be touched means its read-only table, which is maintained internally by the DBA and used lookup table only.
I am using JPA annotations, so please suggest how to handle this.
a source to share
The following should work. Map the object AppStatus
in the table App_Status
:
@Entity
public class AppStatus {
@Id
private Long id;
private String statusDescription;
// getters, setters, hashCode, equals...
}
And declare it with a one-to-one association in an object Application
:
@Entity
public class Application {
@Id
private Long id;
private String appName;
private String appCity;
@OneToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "statusid", nullable = false, insertable = false, updatable = false)
private AppStatus appStatus;
// getters, setters, hashCode, equals...
}
Pay particular attention to the following details:
- I've defined the fetch mode to
EAGER
(note that EAGER is the default if you don't define it) so itAppStatus
will look eagerly loaded on bootApplication
. - I have not defined a cascading option, so no operation will be cascaded from
Application
toAppStatus
. -
to get everything
Application
use FETCH JOINFROM Application a JOIN FETCH a.appStatus
a source to share