Limengyang
Limengyang

Reputation: 65

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:

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?

Upvotes: 3

Views: 2998

Answers (2)

Themis Pyrgiotis
Themis Pyrgiotis

Reputation: 896

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;
}

Upvotes: 1

Guna
Guna

Reputation: 316

Try like this, you can map with one end., for OneToOne and ManyToOne at the receiving end you don't need to mention,

@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;

private Person person;
}

Upvotes: 0

Related Questions