所以我有两个实体:
Person.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
}
Address.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());
我有null应该在哪里设置地址。我也尝试将Person类中的注释更改为:
@OneToMany(mappedBy="person", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
或将CascadeType更改为ALL但没有任何帮助。将地址添加到数据库后,我该怎么做才能将地址加载到personDb对象中?
答案 0 :(得分:0)
这不是最佳解决方案,但尝试在personDB中添加新地址。
Address address = new Address();
address.setPerson(personDb);
personDB.addAddress(address);
personRepo.save(personDB)
答案 1 :(得分:0)
确保此人坚持。
为此进行集成测试。如果您使用的是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;
从那里拿走