在@ Hnenate中使用@OneToOne进行选择时会遇到java.lang.StackOverflowError

时间:2016-06-14 03:16:03

标签: java hibernate jpa spring-data-jpa one-to-one

当我在Hibernate中测试@OneToOne映射关系的一些事情时,我使用spring-data-jpa来查询。对于@OneToOne的双向关系,当我查询实体时,会发生两个条件:

  • 当两个表中没有数据时,没有错误;
  • 当数据存储在两个表中时,只是StackOverflowError;

下一个相关代码:

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

测试代码:

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

我在网站上搜索一些答案,找到相关问题,StackOverFlowError while doing a One-To-One relationship in GAE Datastore using JPA 2.0

但我没有明确地实例化实体,所以没有recurses。使用jpa 2.1 有解决方案吗

2 个答案:

答案 0 :(得分:1)

我在 @OneToOne 关系中遇到了同样的问题,java.lang.StackOverflowError: null 的解决方案是在关系的欠方使用 fetch LAZY

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

答案 1 :(得分:0)

尝试这样,你可以用一端映射。对于接收端的OneToOne和ManyToOne,你不需要提及,

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