简体   繁体   中英

JPA Query with OneToMany

Below is my entities. I try to call ChannelGenre.findByGenreId to retrieve ChannelGenre with channel list. 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. And i can aslo got the correct list when i call 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。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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