簡體   English   中英

JPA / Hibernate雙向多對一導致StackOverflowException

[英]JPA/Hibernate bidirectional many-to-one results in StackOverflowException

我有實體User和GrantedRole具有雙向一對多關系。

當我嘗試將GrantedRole添加到Set in User時,沒有拋出異常,但是當我調試User和GrantedRole對象的變量時,會有一個讀取的描述

com.sun.jdi.InvocationException發生了調用方法。

調試時可以讀取變量的不同字段,但是當我選擇User中的角色字段或GrantedRole中的用戶字段時,我得到與上面相同的描述。 當我進入用戶的Set of GrantedRole時,我最終找到以下描述:

詳細格式化程序錯誤:發生異常:java.lang.StackOverflowError

我的代碼:

public class User {
    private Set<GrantedRole> roles = new HashSet<GrantedRole>();

    public User() {
        super();
    }
    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
    public Set<GrantedRole> getRoles() {
        return roles;
    }

    public void setRoles(Set<GrantedRole> roles) {
        this.roles = roles;
    }

    // equals and hashCode are based on username
    // toString is based on all fields
}

public class GrantedRole {
    private user user;

    public GrantedRole() {
        super();
    }
    public GrantedRole(User user, Role role, Organization organization) {
        this.user = user;
        this.role = role;
        this.organization = organization;
    }

    @ManyToOne
    @NotNull
    public User getUser() {
        return user;
    }

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

    // equals and hashCode are based on all fields
    // toString was based on all fields, I've changed it to not include User.
}

public class Test {
    public void testStuff() {
        User user = new User("name");
        GrantedRole role = new GrantedRole(user, "role"); //this sets the user field
        user.getRoles().add(role); //doesn't throw Exception, but debugging shows InvocationTargetException and StackOverflowException
        System.out.println(user.getRoles()); //throws StackOverflowException, as I would expect
    }
}

我的理解是,我應該能夠以這種方式建立雙向關系。 我閱讀了多個教程, 比如這個 ,我看不出我做的不同,導致.add(角色)出錯。

我遺漏了一些瑣碎的代碼,如果需要,我很樂意提供它。 我沒有制作代碼來確保該用戶引用具有對用戶引用的GrantedRole作為回報,但我認為這與我遇到的問題無關。

所以,我只是愚蠢,並在toString()方法中進行了遞歸調用。 User.toString()嘗試打印角色,GrantedRole.toString()嘗試打印用戶。

我通過改變GrantedRole.toString()來修復它,以打印user.getUsername(),從而打破循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM