所以我有两个实体:
人.java
@Entity
@Table(name = "persons")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToMany(mappedBy="person", cascade = CascadeType.REMOVE)
@JsonIgnoreProperties("person")
private Set<Address> addresses;
//getters and setters
}
地址.java
@Entity
@Table(name = "addresses")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotNull
@ManyToOne
@JoinColumn(name = "person_id", nullable = false)
@JsonIgnoreProperties("addresses")
private Person person;
//getters and setters
}
稍后在我的代码中,我有一个 personDb 对象(已经保存在数据库中(,然后我添加了地址:
Address address = new Address();
address.setPerson(personDb);
address = addressRepository.save(address);
现在我有附加了 person 对象的地址对象,但我的 personDb 仍然没有任何地址附加到它。即使我再次尝试从数据库中获取它:
personRepository.findOne(personDb.getId(((;
我有空,应该在哪里设置地址。我还尝试将我在 Person 类中的注释更改为如下所示的内容:
@OneToMany(mappedBy="person", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
或将级联类型更改为 ALL,但没有任何帮助。将地址添加到数据库后,我可以执行哪些操作才能将地址加载到我的 personDb 对象?
这不是最好的解决方案,但尝试向personDB添加新地址。
Address address = new Address();
address.setPerson(personDb);
personDB.addAddress(address);
personRepo.save(personDB)
确保此人是持久的。
为此,请对其进行集成测试。如果您使用的是 Spring,我还建议您使用内存数据库进行测试。
@Transactional
@Test
public void testFindOneAddress(){
// persist the person
Person person = new Person();
...
personRepository.save(person);
// persist the address
Address address = new Address();
address.setPerson(person);
addressRepository.save(address);
// find the persisted person and addresses
Person queryResult= personRepository.findOne(person.getId());
assertNotNull(queryResult);
assertNotNull(queryResult.getAddresses());
assertEquals(1, queryResult.getAddresses().size());
assertEquals(address.getId(), queryResult.getAddresses().get(0).getId());
}
还要确保您的人员ID列称为"person_id">
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "person_id")
private Integer id;
从那里拿走