我的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;
但我無法像這樣投射這個物體。 有沒有更好的方法來實現這一目標?
對於初學者來說,如果你不改變屬性名稱,'@ JsonProperty'是多餘的。 – chrylis