当我在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;
}


人道:

@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

但是我没有显式实例化该实体,因此没有递归。使用JPA 2.1
有什么办法吗?

最佳答案

尝试这样,您可以在一端进行映射。对于接收端的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;
}

10-07 23:27