Hibernate @OneToOne孩子不坚持

时间:2015-06-10 05:50:51

标签: java spring hibernate jpa spring-roo

我有一个股票实体,它有2个子实体,股票只能是车辆或财产,而不是两者,股票定义如下:

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class Stock {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Version
    @Column(name = "version")
    private Integer version;

    ...

    @OneToOne(mappedBy = "stock", cascade = CascadeType.ALL)
    private StockProperty property;
    private Boolean isProperty;

    @OneToOne(mappedBy = "stock", cascade = CascadeType.ALL)
    private StockVehicle vehicle;
    private Boolean isVehicle;

    ....

}

然后是子实体StockProperty:

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class StockProperty {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Version
    @Column(name = "version")
    private Integer version;

    ....

    @PrimaryKeyJoinColumn
    @OneToOne(cascade = CascadeType.ALL)
    private Stock stock;

    ... more fields containing property details

}

StockVehicle遵循完全相同的模式:

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class StockVehicle {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Version
    @Column(name = "version")
    private Integer version;

    ....

    @PrimaryKeyJoinColumn
    @OneToOne(cascade = CascadeType.ALL)
    private Stock stock;

    ... more fields containing vehicle details

}

当尝试链接两者时,它在数据库中始终为空:

Stock stock = new Stock();
stock.setProperty(new StockProperty());
stock.getProperty().persist();
stock.persist();

或者相反,它在双方都是空的:

Stock stock = new Stock();

... fill in stock details

StockProperty property = new StockProperty();
property.setStock(stock);
... fill in property details

stock.setProperty(property);
stock.persist();

property.persist();

我没有在日志中看到任何错误,但链接从未发生过:

股票的属性字段都是空的:

enter image description here

StockProperty的股票字段均为空:

enter image description here

我正在尝试实现级联删除,所以当我删除Stock时,它必须删除StockProperty,如果可能的话,还要反过来,否则我会把它作为单向引用。

按要求更新SQL:

Hibernate: insert into stock (account, company, created, full_description, ..., is_property, is_vehicle, modified, version) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

Hibernate: select last_insert_id()

Hibernate: insert into stock_property (created, modified, ... , version) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

Hibernate: select last_insert_id()

我没有在stock插入sql中看到属性字段,也没有在stock_property的insert sql中看到stock字段。

1 个答案:

答案 0 :(得分:1)

在StockProperty上试试这个:

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "idStock", nullable = false)
private Stock stock;

这是关于股票的:

@OneToOne(mappedBy="stock")
private StockProperty stockProperty;