0

所以我有两个实体:

人.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);

现在我有地址对象和附加的人员对象,但我的 personDb 仍然没有附加任何地址。即使我再次尝试从数据库中获取它:

personRepository.findOne(personDb.getId());

我有 null 应该在哪里设置地址。我还尝试将 Person 类中的注释更改为以下内容:

@OneToMany(mappedBy="person", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)

或将 CascadeType 更改为 ALL 但没有任何帮助。在将地址添加到数据库后,如何将地址加载到我的 personDb 对象?

4

2 回答 2

0

这不是最佳解决方案,但请尝试向 personDB 添加新地址。

Address address = new Address();
address.setPerson(personDb);
personDB.addAddress(address);
personRepo.save(personDB)
于 2017-06-09T06:57:29.317 回答
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;

从那里拿走

于 2017-06-09T07:06:38.980 回答