#spring #hibernate #jpa #transactions #many-to-many
Вопрос:
У меня есть две сущности, Агентство и Клиент, сопоставленные, как показано ниже, во многих отношениях. Я сохраняю сущность клиента на стороне агентства, и я не могу получить идентификатор клиента после сохранения клиента. Ниже приведены определения сущностей
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Client extends AbstractAuditingEntity{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(mappedBy = "clients")
private Set<Agency> agencys = new HashSet<>();
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Client tag = (Client) o;
return Objects.equals(name, tag.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
и Агентство:
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Agency extends AbstractAuditingEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "agency_client",
joinColumns = @JoinColumn(name = "agency_id"),
inverseJoinColumns = @JoinColumn(name = "client_id")
)
private Set<Client> clients = new HashSet<>();
public void addClient(Client client) {
clients.add(client);
client.getAgencys().add(this);
}
public void removeClient(Client client) {
clients.remove(client);
client.getAgencys().remove(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Agency)) return false;
return id != null amp;amp; id.equals(((Agency) o).getId());
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}
Способ создания клиента:
@Override
@Transactional
public Long save(ClientCreateDto clientCreateDto) {
try {
Client client = new Client();
client.setName(clientCreateDto.getName());
Address address = new Address();
address.setFirstLine(clientCreateDto.getAddress().getFirstLine());
address.setTown(clientCreateDto.getAddress().getTown());
address.setPostcode(clientCreateDto.getAddress().getPostcode());
client.setAddress(address);
client.setEmail(clientCreateDto.getEmail());
client.setBillingEmail(clientCreateDto.getBillingEmail());
client.setTelephone(clientCreateDto.getTelephone());
client.setLogo(clientCreateDto.getLogo());
client.setCreatedBy("System");
client.setStatus(Status.ACTIVE);
client.setService(service.getOne(clientCreateDto.getServiceId()));
Agency agency = agencyService.getOne(clientCreateDto.getAgencyId());
agency.addClient(client);
agencyRepository.saveAndFlush(agency);
log.info("################### Client {}", client.toString());
return client.getId();
} catch (Exception exception) {
throw new BusinessValidationException(exception.getMessage());
}
}
Я получаю значение null вместо идентификатора, выделенного клиенту.
Ответ №1:
Сначала вы должны сохранить объект клиента. Сделай это,
@Override
@Transactional
public Long save(ClientCreateDto clientCreateDto) {
try {
Client client = new Client();
client.setName(clientCreateDto.getName());
Address address = new Address();
address.setFirstLine(clientCreateDto.getAddress().getFirstLine());
address.setTown(clientCreateDto.getAddress().getTown());
address.setPostcode(clientCreateDto.getAddress().getPostcode());
client.setAddress(address);
client.setEmail(clientCreateDto.getEmail());
client.setBillingEmail(clientCreateDto.getBillingEmail());
client.setTelephone(clientCreateDto.getTelephone());
client.setLogo(clientCreateDto.getLogo());
client.setCreatedBy("System");
client.setStatus(Status.ACTIVE);
client.setService(service.getOne(clientCreateDto.getServiceId()));
Agency agency = agencyService.getOne(clientCreateDto.getAgencyId());
//save client
Client savedClient = clientRepository.save(client);
agency.addClient(savedClient);
agencyRepository.saveAndFlush(agency);
log.info("################### Client {}", savedClient.toString());
return savedClient.getId();
} catch (Exception exception) {
throw new BusinessValidationException(exception.getMessage());
}
}