Open JPA Saving OneToMany , foreign key not set

user2023141 picture user2023141 · Jan 29, 2013 · Viewed 21.2k times · Source

I've two tables: TaStock and TaStockPrice. Field tastockid in table TaStockPrice is the foreign key to table 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;
    ...
}

persisting taStock with Children

@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);
}

I read that when persisting a parent class, hibernate automatically persist the children of that class. But instead, the following exception occurs:

javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: ERROR: null value in column "tastockid" violates not-null constraint

Answer

user2023141 picture user2023141 · Feb 11, 2013

I removed private Integer tastockid" from TaStockPrice, and modified @JoinColumn(name = "tastockid", nullable = false, updatable = false, insertable = true) to solve it.