Hibernate 外键上的简单多工单关系错误不可为空

Hibernate 外键上的简单多工单关系错误不可为空,hibernate,spring-boot,foreign-keys,Hibernate,Spring Boot,Foreign Keys,使用SpringBoot和hibernate注释,我希望一个仓库以多对一的关系包含多个BusVehicle。总线车辆也不能分配给车辆段,将其外键标记为空。从我所读到的内容来看,默认情况下它应该可以为null,但在尝试插入我的项时,我遇到了以下错误: There was an unexpected error (type=Internal Server Error, status=500). could not execute statement; SQL [n/a]; constraint ["

使用SpringBoot和hibernate注释,我希望一个仓库以多对一的关系包含多个BusVehicle。总线车辆也不能分配给车辆段,将其外键标记为空。从我所读到的内容来看,默认情况下它应该可以为null,但在尝试插入我的项时,我遇到了以下错误:

There was an unexpected error (type=Internal Server Error, status=500).
could not execute statement; SQL [n/a]; constraint ["FK9ORG94PEJ62WYIS4QS1F2WCP7: PUBLIC.BUSVEHICULE FOREIGN KEY(ID) REFERENCES PUBLIC.DEPOT(ID) (1)"; SQL statement: insert into busvehicule (id, busvehicule_color, fk_depot_id, busvehicule_passengercapacity, busvehicule_platenumber, busvehicule_type) values (null, ?, ?, ?, ?, ?) [23506-199]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
我尝试添加注释,如nullable=true或optional=true,但没有任何更改。我正在使用H2数据库

公共汽车:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne(optional=true)
@JoinColumn(name ="FK_depotId", nullable = true)
private Depot depotParkedIn;
仓库:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "DEPOT_BUSVEHICULESPARKED")
@OneToMany(mappedBy="id", cascade = CascadeType.DETACH, fetch=FetchType.EAGER)
private Set<BusVehicle> busVehiclesParked = new HashSet<BusVehicle>();
保存对象的代码如下:

@Autowired
BusVehicleRepository busVehiculeRepository;

@PostMapping("/createbusvehicle")
public String checkAndCreateBusVehicle (BusVehicle newBusVehicle, Model model) {
    if (!BusVehiculeWrapper.ValidateBusVehicle(newBusVehicle)) {
        return "createBusVehicle";
    }
    busVehiculeRepository.save(newBusVehicle);
    return "mainpage";
}
总线存储库:

@Repository
public interface BusVehicleRepository extends JpaRepository<BusVehicle, Long> {
     public List<BusVehicle> findByDepotParkedInNull();
}
@存储库
公共接口总线存储库扩展了JPA存储库{
公共列表findByDepotParkedInNull();
}
通过我的自定义验证后,存储库中的save方法失败(这不会检查depot是否为null,正如预期的那样)。

您的问题在于:

@OneToMany(mappedBy="id", cascade = CascadeType.DETACH, fetch=FetchType.EAGER)
private Set<BusVehicle> busVehiclesParked = new HashSet<BusVehicle>();
因此,请尝试更改为:

@OneToMany(mappedBy="depotParkedIn", cascade = CascadeType.DETACH, fetch=FetchType.EAGER)
private Set<BusVehicle> busVehiclesParked = new HashSet<BusVehicle>();
@OneToMany(mappedBy=“depotParkedIn”,cascade=CascadeType.DETACH,fetch=FetchType.EAGER)
私有集busVehiclesParked=new HashSet();

仅供参考:这两个实现都在本地进行了测试,并且在这里进行了更改,一切都正常。

Hi@lymn,刚刚用测试过的代码进行了回答。请检查一下,让我知道。谢谢我加了一票:)谢谢@lymn,如果这解决了你的问题,你能关闭它并标记为正确吗?人们知道是什么解决了这个问题?
@ManyToOne
@JoinColumn(name ="FK_depotId")
private Depot depotParkedIn;
@OneToMany(mappedBy="depotParkedIn", cascade = CascadeType.DETACH, fetch=FetchType.EAGER)
private Set<BusVehicle> busVehiclesParked = new HashSet<BusVehicle>();