开发者

How to Map a table with another lookup table using JPA?

I have two tables:

1) Application(int appid, int statusid, String appname, String appcity with g开发者_如何学Cetter and Setter methods)

2) App_Status(int statusid,String statusDescription with setter and getter methods)

I want to map Application table with App_Status so that I don't have to query separately App_Status table in order to get the statusDescription. One thing I have to careful is that no matter what (Insert,update or delete) to the Application table the App_Status table should be unaffected means its a read only table which is maintained by the DBA internally and used only for lookup table.

I am using JPA annotations so please suggest how to handle this.


The following should work. Map an AppStatus entity on the App_Status table:

@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 the Application entity:

@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 a special attention to the following details:

  • I defined the fetch mode to EAGER (note that EAGER is the default if you don't define it) so that the AppStatus will be eagerly fetched when loading an Application.
  • I didn't define any cascading option so that no operation will be cascaded from Application to AppStatus.
  • to retrieve all Application, use a FETCH JOIN

    FROM Application a JOIN FETCH a.appStatus
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜