Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

encounter java.lang.StackOverflowError when used @OneToOne for select in Hibernate

when I test some things about mapping relationship of @OneToOne in Hibernate, and I use spring-data-jpa to query. For the bidirectional relationship of the @OneToOne, when I query an entity, it will occurred two conditions:

  • when no data in two tables, no errors;
  • when data is stored in two tables, just StackOverflowError;

the related code in the next:

@Entity
public class Person {
    @Id
    @GeneratedValue
    private Integer personId;
    private String name;
    @OneToOne
    private IdCard idCard;
    // setter&getter
}

@Entity
public class IdCard {
    @Id
    @GeneratedValue
    private Integer number;
    private String area;

    @OneToOne(mappedBy="idCard")
    private Person person;
}

PersonDao:

@Transactional
@Repository
public interface PersonDao extends CrudRepository<Person, Integer> {
    public Person findByPersonId(Integer personId);
} 

IdCardDao:

@Transactional
@Repository
public interface IdCardDao extends CrudRepository<IdCard, Integer> {
    public IdCard findByNumber (Integer number);
} 

test code:

Person person = personDao.findByPersonId(1);
System.out.println(person);
IdCard idCard = idCardDao.findByNumber(123);
System.out.println(idCard);

I search some answers in the website, find a related question, StackOverFlowError while doing a One-To-One relationship in GAE Datastore using JPA 2.0

but I did not instantiate the entity explicitly, so no recurses. use jpa 2.1 Any solutions?

like image 367
Limengyang Avatar asked Nov 19 '25 19:11

Limengyang


1 Answers

I had the same problem in @OneToOne relationship, and the solution for the java.lang.StackOverflowError: null is to use fetch LAZY in the owing side of the relationship.

@Entity
public class Person {
    @Id
    @GeneratedValue
    private Integer personId;
    private String name;
    @OneToOne (fetch = FetchType.LAZY)
    private IdCard idCard;
    // setter&getter
}

@Entity
public class IdCard {
    @Id
    @GeneratedValue
    private Integer number;
    private String area;

    @OneToOne(mappedBy="idCard")
    private Person person;
}
like image 122
Themis Pyrgiotis Avatar answered Nov 22 '25 08:11

Themis Pyrgiotis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!