问题描述
我在 Spring Jpa 中使用复合主键构建了多对多关联。我的实体是 Client 和 GunType,桥实体是 Rental。我的问题是我想删除一个租赁(我想保持获取类型的渴望)。代码运行无异常,但没有结果。
这些是实体:
public class Client extends BaseEntity<Long> {
private String name;
@Embedded
private Address address;
@OnetoMany(mappedBy = "client",cascade ={CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},fetch = FetchType.EAGER)
@ToString.Exclude
private Set<Rental> rentalSet = new HashSet<>();
}
public class GunType extends BaseEntity<Long> {
private String name;
private Category category;
@OnetoMany(mappedBy = "gunType",fetch = FetchType.EAGER)
private Set<Rental> rentalSet = new HashSet<>();
}
public class Rental implements Serializable {
@Id
@ManyToOne(optional = false,fetch = FetchType.EAGER)
@JoinColumn(name = "client_id")
private Client client;
@Id
@ManyToOne(optional = false,fetch = FetchType.EAGER)
@JoinColumn(name = "guntype_id")
private GunType gunType;
@Column(name = "price")
private Integer price;
}
在服务中的删除方法中,我尝试从两个集合中删除租用,但它仍然没有任何作用:
@Override
@Transactional
public void deleteRental(Long clientId,Long gunTypeId) {
logger.trace("deleteRental - method entered; clientId = {},gunTypeId={}",clientId,gunTypeId);
Client client = clientRepository.findById(clientId).orElseThrow();
Optional<Rental> rentalOptional = client
.getRentalSet()
.stream()
.filter(rental -> rental.getGunType().getId().equals(gunTypeId))
.findFirst();
rentalOptional.ifPresent(
rental -> {
client.getRentalSet().remove(rental);
}
);
GunType gunType = gunTypeRepository.findById(gunTypeId).orElseThrow();
rentalOptional = gunType
.getRentalSet()
.stream()
.filter(rental -> rental.getClient().getId().equals(clientId))
.findFirst();
rentalOptional.ifPresent(
rental -> {
gunType.getRentalSet().remove(rental);
}
);
logger.trace("deleteRental - method finished");
}
我还尝试使用诸如 ophanRemoval 或 CascadeType.ALL 之类的注释来制作它,但这些都没有改变任何东西。或者甚至有可能做到这一点?
解决方法
您只需要删除租赁实体。 (这代表数据库表行,要在连接表中删除)
使用删除方法创建存储库,如下所示:
@Repository
public interface RentalRepository extends CrudRepository {
void deleteByClient_idAndGunType_id(Long clientId,Long gunTypeId);
}