【发布时间】:2019-04-26 20:38:35
【问题描述】:
问题
我有两个实体,Parent 和 Child,我希望它们共享一个主键,但我希望关系是单向的。只有孩子应该知道父母。 spring-data-jpa 存储库可以做到这一点吗?
我尝试过的
我已经尝试直接使用 EntityManager 并且它可以工作。我可以先保留
Parent,然后再保留Child实体。但是,当我尝试使用 Spring 的JpaRepository进行相同操作时,出现以下错误:org.springframework.orm.jpa.JpaSystemException: attempted to assign id from null one-to-one property。我尝试使用自己的 SERIAL id 和对父级的外键引用对
Child实体进行不同的建模。这可行,但我更喜欢使用共享主键。
父实体:
@Entity
public class Parent {
@Id
@Column(name = "code")
String code;
}
子实体:
@Entity
public class Child {
@Id
@Column(name = "code")
String code;
@MapsId
@JoinColumn(name = "code")
@OneToOne
Parent parent;
}
测试:
@RunWith(SpringRunner.class)
@DataJpaTest
@Slf4j
public class MapsByIdTest {
@Autowired
ChildRepository childRepo;
@Autowired
ParentRepo parentRepo;
@Autowired
EntityManager entityManager;
@Test // FAILS with org.springframework.orm.jpa.JpaSystemException
public void testSpringDataJpaRepository() {
Parent pA = parentRepo.save(Parent.builder().code("A").build());
Child child = Child.builder().parent(pA).code("A").build();
childRepo.save(child);
}
@Test // WORKS!
public void testEntityManager() {
Parent p = Parent.builder().code("A").build();
entityManager.persist(p);
Child child = Child.builder().code("A").parent(p).build();
entityManager.persist(child);
log.info(entityManager.find(Parent.class, "A").toString());
log.info(entityManager.find(Child.class, "A").toString());
}
}
【问题讨论】:
标签: hibernate spring-data-jpa one-to-one