Hibernate,查询不检索相关实体

时间:2016-12-01 19:15:43

标签: java postgresql hibernate java-ee-7

我有一个关于查询的问题。

public Event queryEventById(long tmpId) {
    EntityManager manager = entityManagerFactory.createEntityManager();
    return (Event) manager.createQuery("SELECT e FROM Event e WHERE e.id = :id")
            .setParameter("id", tmpId).getSingleResult();
}

这有效,但我有一个问题。 Event有一个实体Organizer的Set(容器),它是Events和Users的连接表。 但是,使用此查询创建的事件会使组织者设置为空。

当持久化时,可以将事件发送到数据库,一切都很好,但检索时却不行。

在活动中,我会检索这样的组织者。

@OneToMany(mappedBy = "event",cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public Set<Organizer> getOrganizers() {
    return this.organizers;
}

组织者实体:

@Entity
@Table(name = "ORGANIZERS")
public class Organizer implements Serializable{

    private static final long serialVersionUID = 1L;

    private long id;
    private User user;
    private Event event;

    @Id
    @GeneratedValue
    @Column(name = "ORGANIZER_ID")
    public long getId() {
        return id;
    }

    public Organizer() {

    }

    public void setId(long id) {
        this.id = id;
    }

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "USER_ID")  
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "EVENT_ID")
    public Event getEvent() {
        return event;
    }

    public void setEvent(Event event) {
        this.event = event;
    }
}

有什么建议吗?

哦,这有点令人沮丧,但我终于找到了问题。

    @OneToMany(mappedBy = "event",cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public Set<Organizer> getOrganizers() {
    return this.organizers;
}

mappedBy设置为组织者而不是事件。

0 个答案:

没有答案