2017-04-11 38 views
0

我的Spring應用程序使用JSON API,然後使用JPA將它保存在數據庫中。我正面臨着設計合理的實體和模型的問題。如何構建JPA實體和JSON模型?

我的模型JSON的樣子:

@Data 
@Setter(AccessLevel.NONE) 
@JsonIgnoreProperties(ignoreUnknown = true) 
public class TvShowRemote implements TvShowEntity { 
    @JsonProperty("id") 
    public Integer id; 
    @JsonProperty("url") 
    public String url; 
    @JsonProperty("name") 
    public String name; 
    @JsonProperty("summary") 
    public String summary; 
    @JsonProperty("updated") 
    public Integer updated; 
    @JsonProperty("_embedded") 
    public Embedded embedded; 

    public List<SeasonEntity> getSeasons() { 
     return new ArrayList<SeasonEntity>(embedded.getSeasons()); 
    } 

    public List<EpisodeEntity> getEpisodes() { 
     return new ArrayList<EpisodeEntity>(embedded.getEpisodes()); 
    } 
} 

我JPA entites的樣子:

@Data 
@Setter(AccessLevel.NONE) 
@Entity 
@Table(name = "TvShows") 
public class TvShowLocal implements TvShowEntity { 

    @Id 
    @GeneratedValue 
    public Integer id; 

    public Integer tvShowId; 

    public String name; 

    public Integer runtime; 

    public String summary; 

    @Column(name = "seasons") 
    @OneToMany 
    @ElementCollection(targetClass = SeasonLocal.class) 
    public List<SeasonLocal> seasons; 

    @Column(name = "episodes") 
    @OneToMany 
    @ElementCollection(targetClass = EpisodeLocal.class) 
    public List<EpisodeLocal> episodes; 

    @Override 
    public List<SeasonEntity> getSeasons() { 
     return new ArrayList<SeasonEntity>(seasons); 
    } 

    @Override 
    public List<EpisodeEntity> getEpisodes() { 
     return new ArrayList<EpisodeEntity>(episodes); 
    } 
} 

龍目島標註@Data自動實現的getter/setter方法。 我試圖實現這兩個類接口:

public interface TvShowEntity { 

    Integer getId(); 

    String getName(); 

    List getSeasons(); 

    List getEpisodes(); 
} 

還有兩種接口SeasonEntity,EpisodeEntity我在SeasonRemote,SeasonLocal,EpisodeRemote,EpisodeLocal實施。他們看起來像上面的例子。

現在我試圖將TvShowRemote分配給TvShowLocal;

TvShowEntity tvshowEntity = new TvShowRemote(); 
TvShowLocal tvShowLocal = (TvShowLocal) tvShowEntity; 

但我無法像這樣投射這個物體。 有沒有更好的方法來實現這一目標?

+0

對於初學者來說,如果你不改變屬性名稱,'@ JsonProperty'是多餘的。 – chrylis

回答

0
TvShowEntity tvshowEntity = new TvShowRemote(); 
TvShowLocal tvShowLocal = (TvShowLocal) tvShowEntity; 

你試圖實現不可能投不能做。

TvShowRemoteTvShowEntity

TvShowLocalTvShowEntity

這並不意味着TvShowRemoteTvShowLocal,反之亦然。

您可以使用適配器設計模式。

+0

謝謝你的回答。我知道演員不能做。這就是爲什麼我問它可能以更好(適當)的方式實現這一點。我如何創建可以輕鬆分配TvShowRemote - > TvShowLocal的模型類? – Hype

+0

使用適配器設計模式,或者只是通過編碼手動執行你的投影 –

+0

謝謝!我將使用適配器。 – Hype

0

我看到TvShowEntity和TvShowLocal都擴展了TvShowEntity。 但是你不能投射一個TvShowEntity作爲TvShowRemote被實例化爲一個TvShowLocal。

Wideskills

演員可以到自己的類類型或它的子類或超類或接口中的一個。

您應該TvShowRemote手動複製屬性TvShowLocal或只使用超TvShowEntity如果聲明所有需要的方法的接口。