简体   繁体   中英

Fetch many to one hibernate in JSP

How can I fetch a many to one relationship in a JSP page? I tried

<s:property value="group.division.name" />

but no data appeared on the JSP.

The Group can belong to one Division .

public class Group implements java.io.Serializable {
    ..
    private Division division;
    ..

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "div_id", nullable = false)
    public Division getDivision() {
            return this.division;
    }

    public void setDivision(Division division) {
            this.division = division;
    }
}

And

public class Division implements java.io.Serializable {
    ...
    private String name;
    private Set<Group> groups = new HashSet<Group>(0);

    @Column(name = "name", nullable = false, length = 50)
    public String getName() {
            return this.name;
    }

    public void setName(String name) {
            this.name = name;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "division")
    public Set<Group> getGroups() {
            return this.groups;
    }

    public void setGroups(Set<Group> groups) {
            this.groups = groups;
    }
}

I think, its because of your FetchType.LAZY . Remove that part, it'll fetch it eagerly by default, if I'm not mistaken -- didn't touch Hibernate for a long time, since its @ManyToOne .

EAGER will try to use an outer join to retrieve the associated object, while LAZY will only trigger an explicit SELECT statement when the associated object is accessed for the first time. Now, here is caveat, the LAZY thing will only work, and fire an explicit SELECT to load the related entities, within the transaction. In your case, the transaction is already ended, it seems; therefore its not able to retrieve the related entity.

You might like to read this question here , it discussed this thing briefly, in the question and one of the answer.

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