我有两个表: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;
...
}
坚持与孩子一起工作
@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);
}
我读到在持久化父类时,休眠会自动持久化该类的子类。但相反,会发生以下异常:
javax.persistence.PersistenceException:org.hibernate.exception.ConstraintViolationException:错误:“tastockid”列中的空值违反非空约束