Hibernate JPA一对多主键不会级联为另一个表中的外键


@Entity
@Table(name="property")
@NamedQuery(name="Property.findAll", query="SELECT p FROM Property p")
public class Property implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "property_seq")
@SequenceGenerator(name = "property_seq", allocationSize = 1, sequenceName = "s_property")
@Column(name="property_id", unique=true, nullable=false, precision=10)
private long propertyId;
@Column(name="prop_size", nullable=false, precision=10, scale=4)
private BigDecimal propSize;
@Column(name="schdule_all_day_flag")
private Boolean schduleAllDayFlag;
@Column(name="schdule_prop_end_time", length=25)
private String schdulePropEndTime;
@Column(name="schdule_prop_start_time", length=25)
private String schdulePropStartTime;
@Column(name="secondary_phone", precision=10)
private BigDecimal secondaryPhone;
@Column(length=500)
private String street;
//bi-directional many-to-one association to PropertyAmenity
@OneToMany(mappedBy="property", cascade = CascadeType.ALL)
private List<PropertyAmenity> propertyAmenities;
}
@Entity
@Table(name="property_amenities")
@NamedQuery(name="PropertyAmenity.findAll", query="SELECT p FROM PropertyAmenity p")
public class PropertyAmenity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "property_amenity")
@SequenceGenerator(name = "property_amenity", allocationSize = 1, sequenceName = "s_property_amenities")
@Column(name="property_amenities_id", unique=true, nullable=false, precision=10)
private long propertyAmenitiesId;
@Column(name="avilable_flag", nullable=false)
private Boolean avilableFlag;
@Column(name="last_updated_by", length=50)
private String lastUpdatedBy;
@Column(name="last_updated_date")
private Timestamp lastUpdatedDate;
@Column(name="master_amenity_type", nullable=false, length=10)
private String masterAmenityType;
//bi-directional many-to-one association to Property
@ManyToOne
@JoinColumn(name="property_id")
private Property property;
}

在我们的项目中,需要将物业和物业便利设施实体存储到数据库中。这个表之间的关系是property_id充当property中的主键,FK充当property Amenities表中的主键。当使用propertySearchRepository.save(property(保存数据时,property表中的property_id PK不会作为FK级联到property Amenities表并获得null值。

2021-06-09 00:20:33.347[http-nio-9000-exec-2]错误o.h.e.jdbc.spi.SqlExceptionHelper-错误:列中的空值;property_id";违反非空约束

我使用的是spring.jpa.hibernate.ddl auto=none,我们不应该在生产中使用ddl命令。请说明如何将主键级联到子表。

我建议您的第一件事是为集合设置默认值。在您的情况下,可以使用空的ArrayList初始化propertyAmenities

@OneToMany(mappedBy="property", cascade = CascadeType.ALL)
private List<PropertyAmenity> propertyAmenities = new ArrayList<>();

然后,在保存实体之前,您需要像这样设置关系的两侧

Property property = new Property();
PropertyAmenity propertyAmenity = new PropertyAmenity();
property.getPropertyAmenities().add(propertyAmenity);
propertyAmenity.setProperty(property);
propertySearchRepository.save(property);

相关内容

最新更新