How to load only ids from Many to Many mapping tables?

前端 未结 2 988
时光说笑
时光说笑 2020-12-30 04:35

In a Many to Many relation between two table with a Mapping table in between, how can I only load ids for the second entity.

Following is the example to explain what

2条回答
  •  感情败类
    2020-12-30 05:01

    I encountered a problem with the accepted answer, when I wanted to map both pages and pageIds. Hibernate will use both of these fields to make changes to the mapping table when a User is saved, possibly causing a lot of weird behaviour.

    I instead solved this by making pageIds @Transient and populating the collection using @PostLoad:

    @ManyToMany
    @JoinTable(
        name="user_page",
        joinColumns = @JoinColumn(name="id_user"),
        inverseJoinColumns = @JoinColumn(name="id_page")
    )
    public Set pages;
    
    @Transient
    public Set pageIds;
    
    @PostLoad
    private void postLoad() {
        pageIds = pages.stream().map(Page::getId).collect(Collectors.toSet());
    }
    

提交回复
热议问题