当我在Hibernate中测试@OneToOne映射关系的一些事情时,我使用spring-data-jpa来查询。对于@OneToOne的双向关系,当我查询实体时,会发生两个条件:
下一个相关代码:
@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 有解决方案吗
答案 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;
}