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.

+2


a source to share


1 answer


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 it AppStatus

    will look eagerly loaded on boot Application

    .
  • I have not defined a cascading option, so no operation will be cascaded from Application

    to AppStatus

    .
  • to get everything Application

    use FETCH JOIN

    FROM Application a JOIN FETCH a.appStatus
    
          

+2


a source







All Articles