gpt4 book ai didi

java - Hibernate 生成额外的表

转载 作者:行者123 更新时间:2023-11-30 10:05:44 24 4
gpt4 key购买 nike

我有一个这样的实体

@Entity
@Table(name = "past_price")
public class PastPrice {

@Id
private String symbol;
@OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
private Set<Price> prices = null;

public String getSymbol() {
return symbol;
}

public void setSymbol(String symbol) {
this.symbol = symbol;
}

public Set<Price> getPrices() {
return prices;
}

public void setPrices(Set<Price> prices) {
this.prices = prices;
}

}

Price实体是这样的

@Entity
public class Price {
@Id
@Temporal(TemporalType.TIMESTAMP)
private Date date;
private String price;

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}

public String getPrice() {
return price;
}

public void setPrice(String price) {
this.price = price;
}

}

我想做的是,创建一个名为 past_price 的表,它与 Price 实体有 OneToMany 关系。我有 hibernate 属性 spring.jpa.hibernate.ddl-auto=update 所以每当我运行它时都会创建 3 个表 1。过去的价格 2。 past_price_prices3。价格。但我只是想创建 2 个表 past_priceprice。任何帮助,将不胜感激。谢谢

最佳答案

使用@JoinColumn 告诉hibernate 在价格表中创建一个列并将其用于连接。将您的代码更改为以下内容:

@OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
@JoinColumn(name = "fk_past_price")
private Set<Price> prices = null;

这将在价格表中创建一个名为 fk_past_price 的列,并且不会创建第三个表。

P.S.:如果没有充分的理由使用单向关联,请改用双向关联。如下所示:

@Entity
@Table(name = "past_price")
public class PastPrice {

@Id
private String symbol;
@OneToMany(mappedBy = "pastPrice", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Price> prices = null;

public String getSymbol() {
return symbol;
}

public void setSymbol(String symbol) {
this.symbol = symbol;
}

public Set<Price> getPrices() {
return prices;
}

public void setPrices(Set<Price> prices) {
this.prices = prices;
}

}

价格:

@Entity
public class Price {
@Id
@Temporal(TemporalType.TIMESTAMP)
private Date date;
private String price;

@ManyToOne
@JoinColumn(name = "past_price_symbol", nullable = false)
private PastPrice pastPrice;

public PastPrice getPastPrice() {
return pastPrice;
}

public void setPastPrice(PastPrice pastPrice) {
this.pastPrice = pastPrice;
}

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}

public String getPrice() {
return price;
}

public void setPrice(String price) {
this.price = price;
}

}

关于java - Hibernate 生成额外的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55095809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com