[英]Generate database using hibernate annontation (foreign key not found)
I am trying to create OneToOne relation using Hiberate/JPA between two classes Stock and StockDetails, so when i generate the database I'm not seeing the foreign key in the StockDetail table that should reference Stock, this is my codes : 我正在尝试使用Hiberate / JPA在两个类Stock和StockDetails之间创建OneToOne关系,因此当我生成数据库时,我没有在应该引用Stock的StockDetail表中看到外键,这是我的代码:
Stock 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 : StockDetail类别:
@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;
}
}
I found one topic about the same issue, but it didn't resolve my probleme: 我找到了一个与同一问题有关的主题,但未能解决我的问题:
You got to do something like this in StockDetail 您必须在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;
}
}
The issue with your configuration is that you are trying to make stock_id as primary key of stock_detail with the following configuration. 配置的问题在于,您尝试使用以下配置将stock_id作为stock_detail的主键。
@Id
@GeneratedValue(generator = "generator")
@Column(name = "Stock_Id", unique = true, nullable = false)
Instead what you should do is have a stock_detail_id as primary key of stock_details. 相反,您应该做的是将stock_detail_id作为stock_details的主键。 Since you have a bi-directional one-to-one mapping between both the entities hibernate will automatically generate the foreign key with above mapping.
由于您在两个实体之间都有双向的一对一映射,因此休眠将自动使用上述映射生成外键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.