问题
这是我第一次使用JPA。我有2个实体:Component
和Manufacturer
,关系为ManyToOne
,厂商ID为Component中的外键,只删除外键,当我试图将一个Component的ID置空保存时,出现如下异常:
"identifier of an instance of spring.model.Manufacturer was altered
from 1 to null; nested exception is org.hibernate.HibernateException: identifier of an
instance of spring.model.Manufacturer was altered from 1 to null",
ER图
型号
基本实体
@Data
@MappedSuperclass
public class BaseEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
}
组件
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "Components")
public class Component extends BaseEntity {
@Column(nullable = false)
private String type;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private Double price;
@Column(nullable = false, length = 2048)
private String description;
@Column(nullable = false)
private Integer rating;
@ManyToOne()
@JoinColumn(name = "manufacturerId")
private Manufacturer manufacturer;
}
制造商
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "Manufacturers")
public class Manufacturer extends BaseEntity {
@Column(nullable = false, unique = true)
private String name;
@Column(nullable = false)
private Integer foundingYear;
@Column(nullable = false)
private Double revenue;
@OneToMany(mappedBy = "manufacturer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Component> components = new ArrayList<>();
}
当前代码
@DeleteMapping
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteComponentManufacturer(@PathVariable("componentId") Long id) {
Optional<Component> component = componentDao.findById(id);
if (component.isEmpty()) {
throw new BadRequestException("Could not delete component's (ID: " + id + ") manufacturer");
}
if (component.get().getManufacturer() == null) {
throw new BadRequestException("Component with ID: " + id + " has no manufacturer");
}
component.get().getManufacturer().setId(null);
componentDao.save(component.get()); // Error is thrown here
}
1条答案
按热度按时间9ceoxa921#
您在此处将制造商的ID从原来的任何值设置为
null
:当你调用
.getManufacturer()
时,你将得到链接到 manufacturer 表中记录的实际实体。当你对该对象调用.setId(null)
时,你将修改制造商。我怀疑您 * 尝试 * 做的是将组件与制造商解除关联,因此在 component 记录中,
manufacturerid
为空。