打开JPA Saving OneToMany,未设置外键

时间:2013-01-29 21:51:14

标签: 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;
    ...
}

坚持与儿童保持联系

@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会自动保持该类的子节点。但相反,会发生以下异常:

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

4 个答案:

答案 0 :(得分:6)

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

解决。

答案 1 :(得分:2)

您将集合设置为不可插入也不可更新。这样hibernate永远不会持久化。

您可以设置hibernate如何使用注释中的级联设置来处理此关系。有关详细信息,请参阅此主题的完整博客文章:http://www.mkyong.com/hibernate/hibernate-cascade-example-save-update-delete-and-delete-orphan/

答案 2 :(得分:1)

tastockpriceList上使用以下注释。

@OneToMany
  @Cascade(CascadeType.ALL)
  @JoinColumn(name="tastock")

这应解决问题。

答案 3 :(得分:1)

为了在@OneToMany关系上启用保存功能,例如

@OneToMany(mappedBy="myTable", cascade=CascadeType.ALL)
private List<item> items;

然后你必须告诉你的@ManyToOne关系被允许更新myTable,就像这个updatable = true

@ManyToOne
@JoinColumn(name="fk_myTable", nullable = false, updatable = true, insertable = true)