我有2个实体Client和Address,它们之间具有一对多的关系,如下所示,该客户实体具有一个存储库,而addresse则没有,请问在业务中使用Java 8更新地址的最佳方法是什么层? 两个实体都使用龙目岛注释
@Entity
@Builder
@Getter
@Setter
@AllArgsConstructor
@RequiredArgsConstructor(staticName = "of")
@NoArgsConstructor
@ToString()
@EqualsAndHashCode()
public class Client {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(columnDefinition="LONGTEXT")
private String commentaire;
@Embedded
private Contact contact
@OneToMany(cascade =
{CascadeType.PERSIST,CascadeType.REMOVE},orphanRemoval = true)
@Builder.Default
@OrderBy("id")
private Set<Adresse> adresses = new HashSet<>();
}
public class Adresse {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String cite;
@NonNull
private String pays;
private String region;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "client_id")
private Client client;
}
这是我的方法更新客户端
@Service
@Transactional
public class ClientServiceImpl implements ClientService {
@Autowired
private ClientRepository clientRepository;
public Client update(Client newClient) {
return clientRepository.findById(newClient.getId()).map(client->{
client.setNom_Client(newClient.getNom_Client());
client.setDomaine_Client(newClient.getDomaine_Client());
client.setCommentaire(newClient.getCommentaire());
client.setContact(Contact.builder().nom(newClient.getContact().getNom()).prenom(newClient.getContact().getPrenom()).email(newClient.getContact().getEmail()).telephone(newClient.getContact().getTelephone()).build());
missing code client.getAdresses().addAll(newClient.getAdresses().stream().filter(a->a.getId()==null).collect(Collectors.toSet()));
}
return clientRepository.save(client);
}).orElseGet(()->{return clientRepository.save(newClient);});
}}
期望值:如果没有id_adresse,则向现有Set中添加一个新地址,否则在同一笔交易中更新具有id的字段,那么如何更新实体地址?预先谢谢你