我正在尝试在两个类Stock和StockDetails之间使用Hiberate / JPA创建OneToOne关系,所以当我生成数据库时,我没有在StockDetail表中看到应该引用Stock的外键,这是我的代码:< / p>
股票Classe:
@Entity
@Table(name = "stock", catalog = "migration")
public class Stock implements java.io.Serializable {
private Integer Stock_Id;
private StockDetail stockDetail;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "Stock_Id", nullable = false)
public Integer getStock_Id() {
return this.Stock_Id;
}
@OneToOne(fetch = FetchType.LAZY, mappedBy = "stock", cascade = CascadeType.ALL)
public StockDetail getStockDetail() {
return this.stockDetail;
}
}
StockDetail Classe:
@Entity
@Table(name = "detail_stock", catalog = "migration")
public class StockDetail implements java.io.Serializable {
private Integer Stock_Id;
private Stock stock;
@GenericGenerator(name = "generator", strategy = "foreign",
parameters = @Parameter(name = "property", value = "stock"))
@Id
@GeneratedValue(generator = "generator")
@Column(name = "Stock_Id", unique = true, nullable = false)
public Integer getStock_Id() {
return this.Stock_Id;
}
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public Stock getStock() {
return this.stock;
}
}
我找到了一个关于同一问题的话题,但它没有解决我的问题:
答案 0 :(得分:0)
你必须在StockDetail中做这样的事情
@Entity
@Table(name = "detail_stock", catalog = "migration")
public class StockDetail implements java.io.Serializable {
private Integer stockDetailId;
private Stock stock;
@OneToOne(fetch = FetchType.LAZY)
public Stock getStock() {
return this.stock;
}
/**
* @param stock
* the stock to set
*/
public void setStock(Stock stock) {
this.stock = stock;
}
/**
* @return the stockDetailId
*/
@Id
public Integer getStockDetailId() {
return stockDetailId;
}
/**
* @param stockDetailId the stockDetailId to set
*/
public void setStockDetailId(Integer stockDetailId) {
this.stockDetailId = stockDetailId;
}
}
您的配置问题在于您尝试使用以下配置将stock_id作为stock_detail的主键。
@Id
@GeneratedValue(generator = "generator")
@Column(name = "Stock_Id", unique = true, nullable = false)
相反,你应该做的是将stock_detail_id作为stock_details的主键。由于你在两个实体之间都有一个双向的一对一映射,因此hibernate将自动生成具有上述映射的外键。