简体   繁体   中英

java.lang.StackOverflowError while accessing data using hibernate

I am getting an error when i am trying to join 2 tables in hibernate. Copied code here.

/*ADDRESS table entity mapping */

@Entity
@Table(name = "ADDRESS")
public class AddressEntity {

    @ManyToOne(fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
    @JoinColumn(name = "user_id")
    private UserEntity user;

    // setters and getters and other attributes.

}


/* APPUSER table entity mapping */

@Entity
@Table(name = "APPUSER")
public class UserEntity {

    @Id
    @GeneratedValue
    @Column(name = "USER_ID")
    private Long userId;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
    private Set<AddressEntity> addresses;

    // setters and getters and other attributes.

}

Problem is with mapping of address and user entities. Each user can have multiple addresses this is the requirement. Please help.

Copied Tables DDL statements below.It is one to many relationship between user and address table.

SQLs tables :

CREATE TABLE `appuser` (
    `user_id` int(11) NOT NULL AUTO_INCREMENT,
    `first_name` varchar(255) NOT NULL,
    `last_name` varchar(255) DEFAULT NULL,
    `email_address` varchar(1024) NOT NULL,
    `password` varchar(1024) NOT NULL,
    `active` tinyint(1) DEFAULT '1',
    `popularity_rating` int(11) DEFAULT NULL,
    `join_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8

CREATE TABLE `address` (
    `address_id` int(11) NOT NULL AUTO_INCREMENT,
    `address_line1` varchar(38) NOT NULL,
    `address_line2` varchar(38) NOT NULL,
    `city` varchar(38) NOT NULL,
    `state` varchar(38) NOT NULL,
    `zip` varchar(10) NOT NULL,
    `address_type` varchar(45) NOT NULL,
    `user_id` int(11) NOT NULL,
    PRIMARY KEY (`address_id`),
    KEY `fk_address_user_idx` (`user_id`),
    CONSTRAINT `fk_address_user` FOREIGN KEY (`user_id`) REFERENCES `appuser` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8

Above joining ADDRESS and USER tables giving me StackOverflowError.

Expected result is :

{
    "userId": 1,
    "firstName": "alb",
    "lastName": "va",
    "emailAddress": "alb@va.com",
    "password": "albva",
    "addresses": [
        {
            "addressLine1": "222 plano pkwy",
            "addressLine2": "apt 22",
            "city": "plano",
            "state": "tx",
            "zip": "75034",
            "country": null
        }, {
            "addressLine1": "555 plano pkwy",
            "addressLine2": "apt 11",
            "city": "plano",
            "state": "tx",
            "zip": "75024",
            "country": null
        }
    ],
    "popularityRating": 6,
    "joinDate": 1504897922000,
    "roles": []
}

Result I am getting while calling the web service is an infinite loop.Which is Causing stack overflow error :

{"userId":2,"firstName":"rax","lastName":"tax","emailAddress":"rax@tax.com","password":"raxtax","addresses":[{"addressLine1":"2001 spring creek","addressLine2":"apt 724","city":"plano","state":"tx","zip":"75074","country":null,"addressType":null,"user":{"userId":2,"firstName":"rax","lastName":"tax","emailAddress":"rax@tax.com","password":"raxtax","addresses":[{"addressLine1":"2001 spring creek","addressLine2":"apt 724","city":"plano","state":"tx","zip":"75074","country":null,"addressType":null,"user":{"userId":2,"firstName":"rax","lastName":"tax","emailAddress":"rax@tax.com","password":"raxtax","addresses":[{"addressLine1":"2001 spring creek","addressLine2":"apt 724","city":"plano","state":"tx","zip":"75074","country":null,"addressType":null,"user":{"userId":2,"firstName":"rax","lastName":"tax","emailAddress":"rax@tax.com","password":"raxtax","addresses":[{"addressLine1":"2001 spring creek","addressLine2":"apt 724","city":"plano","state":"tx","zip":"75074","country":null,"addressType":null,"user":{"userId":2,"firstName":"rax","lastName":"tax","emailAddress":"rax@tax.com","password":"raxtax","addresses":[{"addressLine1":"2001 spring creek","addressLine2":"apt 724","city":"plano","state":"tx","zip":"75074","country":null,"addressType":null,"user":{"userId":2,"firstName":"rax","lastName":"tax","emailAddress":"rax@tax.com","password":"raxtax","addresses":[{"addressLine1":"2001 spring creek","addressLine2":"apt 724","city":"plano","state":"tx","zip":"75074","country":null,"addressType":null,"user":{"userId":2,"firstName":"rax","lastName":"tax","emailAddress":"rax@tax.com","password":"raxtax","addresses":[{"addressLine1":"2001 spring creek","addressLine2":"apt 724","city":"plano","state":"tx","zip":"75074","country":null,"addressType":null,"user": ...

When you try to join two tables that depend on each other as you mentioned, there is bound to be an infinite loop because Table A tries to fetch data from Table B. Table B has a dependency to Table A and tries to fetch the data from Table A. It runs into an infinite loop and continues hereby causing the stack overflow exception. The solution to this is to annotate your fields with @JsonManagedReference and @JsonBackReference. With this, the class marked with @JsonManagedReference gets serialized while the one marked with @JsonBackReference doesn't. This breaks the infinite loop. In your code, your entities would look like this;

/*ADDRESS table entity mapping */

@Entity
@Table(name = "ADDRESS")
public class AddressEntity {

@ManyToOne(fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
@JoinColumn(name = "user_id")
@JsonBackReference
private UserEntity user;

// setters and getters and other attributes.

}


/* APPUSER table entity mapping */

@Entity
@Table(name = "APPUSER")
public class UserEntity {

@Id
@GeneratedValue
@Column(name = "USER_ID")
private Long userId;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
@JsonManagedReference
private Set<AddressEntity> addresses;

// setters and getters and other attributes.

}

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