10

我有两个表: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”列中的空值违反非空约束

4

4 回答 4

9

private Integer tastockid"从中删除TaStockPrice,并进行了修改 @JoinColumn(name = "tastockid", nullable = false, updatable = false, insertable = true)以解决它。

于 2013-02-11T19:48:40.297 回答
3

您将集合设置为不可插入或不可更新。这种方式hibernate永远不会持久化它。

您可以使用注释中的级联设置来设置休眠应如何处理此关系。欲了解更多信息,这里有一篇关于该主题的详尽博文:http ://www.mkyong.com/hibernate/hibernate-cascade-example-save-update-delete-and-delete-orphan/ 。

于 2013-01-29T22:53:34.233 回答
2

使用下面的注释tastockpriceList

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

那应该可以解决问题。

于 2013-05-22T14:34:50.403 回答
2

为了启用@OneToMany关系的保存能力,例如

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

然后你必须告诉你的@ManyToOne关系是允许像这样更新 myTable 的 updateable = true

@ManyToOne
@JoinColumn(name="fk_myTable", nullable = false, updatable = true, insertable = true)
于 2015-07-19T09:00:29.123 回答