然后,我的使用JSON API的spring应用程序使用JPA将其保存在数据库中。我面临着设计合理的实体和模型的问题。

我的模型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实体看起来像:

@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();
}


我在SeasonRemote,SeasonLocal,EpisodeRemote和EpisodeLocal中实现了两个接口SeasonEntity,EpisentEntity。它们看起来像上面的示例。

现在,我尝试将TvShowRemote分配给TvShowLocal;

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


但是我不能像这样铸造这个物体。
有更好的方法来实现这一目标吗?

最佳答案

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


您正在尝试实现无法完成的不可能的转换。

TvShowRemoteTvShowEntity



TvShowLocalTvShowEntity

这并不意味着TvShowRemoteTvShowLocal,反之亦然。

您可以使用适配器设计模式。

关于java - 如何构造JPA实体和JSON模型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43352970/

10-12 12:48
查看更多