简体   繁体   English

使用OneToMany进行JPA查询

[英]JPA Query with OneToMany

Below is my entities. 以下是我的实体。 I try to call ChannelGenre.findByGenreId to retrieve ChannelGenre with channel list. 我尝试调用ChannelGenre.findByGenreId来检索带有频道列表的ChannelGenre。 But i got the correct data after i save at the fisrt time, and I only got an ChannelGenre with empty channel list and other correct properties at any other time. 但是在第一时间保存后,我得到了正确的数据,而在其他任何时间,我只得到了一个带有空频道列表和其他正确属性的ChannelGenre。 And i can aslo got the correct list when i call Channel.findAll(). 当我调用Channel.findAll()时,我也可以得到正确的列表。 What's wrong with my codes? 我的代码有什么问题?

@Entity
public class ChannelGenre extends Model {

    @OneToMany(mappedBy = "channelGenre", cascade = CascadeType.ALL)
    private List<Channel> channelList;

    @Required
    private String genreId;

    @SerializedName("genreName")
    @Expose
    @Required
    private String genreName;

    private Boolean isAdult;

    public static void renewChannelGenre(ChannelGenre channelGenre) {
        ChannelGenre cg = ChannelGenre.find("byGenreId", channelGenre.getGenreId()).first();
        if (null != cg) {
            ChannelGenre.deleteByGenreId(channelGenre.getGenreId());
        }
        channelGenre.save();
    }

    public static ChannelGenre findByGenreId(String genreId) {
        return (ChannelGenre) ChannelGenre.find("select cg from ChannelGenre cg where cg.genreId = '" + genreId + "'").fetch().get(0);
    }

    public static void deleteByGenreId(String genreId) {
        ChannelGenre.delete("delete from ChannelGenre cg where cg.genreId = '" + genreId + "'");
    }

    public static List<ChannelGenre> findAllGenreName() {
        return ChannelGenre.find("select distinct cg from ChannelGenre cg order by cg.genreId").fetch();
    }

    @Override
    public String toString() {
        return "ChannelGenre [channelList=" + channelList + ", genreId=" + genreId + ", genreName=" + genreName + ", isAdult=" + isAdult + "]";
    }
}

@Entity
public class Channel extends Model {

    @SerializedName("channelId")
    @Expose
    private String channelId;

    @SerializedName("name")
    @Expose
    private String name;

    @ManyToOne
    private ChannelGenre channelGenre;
}

data i got: 我得到的数据:

At the first time i call. 第一次我打电话。

ChannelGenre [channelList=[Channel [channelId=600, name=Sports Schedule Highlights], Channel [channelId=610, name=Now 610], Chann..., genreId=G07, genreName=Sports, isAdult=false]

At the other times. 在其他时间。

ChannelGenre [channelList=[], genreId=G07, genreName=Sports, isAdult=false]

继续,我的错误是我在保存之前忘记设置channel.channelgenre。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM