打开JPA Saving OneToMany,未设置外键

use*_*141 7 java openjpa

我有两张桌子: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;
    ...
}
Run Code Online (Sandbox Code Playgroud)

坚持与儿童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);
}
Run Code Online (Sandbox Code Playgroud)

我读到,当持久化父类时,hibernate会自动保持该类的子节点.但相反,会发生以下异常:

javax.persistence.PersistenceException:org.hibernate.exception.ConstraintViolationException:错误:"tastockid"列中的空值违反非空约束

use*_*141 6

我从TaStockPrice中删除了"private Integer tastockid",修改了@JoinColumn(name ="tastockid",nullable = false,updatable = false,insertable = true)

解决了.