我有两个表:TaStock和TaStockPrice。表TaStockPrice中的字段tastockid是表TaStock的外键。
@Entity
public class TaStock {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id
@OneToMany(mappedBy = "taStock", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<TaStockPrice> tastockpriceList;
public void addTaStockPrice(TaStockPrice taStockPrice) {
if (taStockPrice == null) {
return;
}
taStockPrice.setTaStock(this);
if (tastockpriceList == null) {
tastockpriceList = new ArrayList<TaStockPrice>();
tastockpriceList.add(taStockPrice);
} else if (!tastockpriceList.contains(taStockPrice)) {
tastockpriceList.add(taStockPrice);
}
}
....
}
@Entity
public class TaStockPrice {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id
@Column
private Integer tastockid;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "tastockid", nullable = false, updatable = false, insertable = false)
private TaStock taStock;
...
}
与 child 保持taStock
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void createTaStock() throws Exception {
TaStock taStock = new TaStock();
...
TaStockPrice taStockPrice = new TaStockPrice();
...
taStock.addTaStockPrice(taStockPrice);
taStockService.persist(taStock);
}
我读到,在保留父类时, hibernate 会自动保留该类的 child 。但是,会发生以下异常:
javax.persistence.PersistenceException:org.hibernate.exception.ConstraintViolationException:错误:“tastockid”列中的空值违反了非空约束
最佳答案
我从private Integer tastockid"
中删除了TaStockPrice
,并进行了修改@JoinColumn(name = "tastockid", nullable = false, updatable = false, insertable = true)
解决。