我有一个股票实体,其中有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
}
尝试链接两者时,在数据库中始终为null:
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();
我没有在日志中看到任何错误,但是链接从未发生:
股票的属性字段均为空:
StockProperty的库存字段全部为空:
我正在尝试实现级联删除,因此,当我删除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中的property字段,也看不到stock_property的插入sql中的stock字段。
最佳答案
在StockProperty上尝试:
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "idStock", nullable = false)
private Stock stock;
这在股票上:
@OneToOne(mappedBy="stock")
private StockProperty stockProperty;