gpt4 book ai didi

java - @PrimaryKeyJoinColumn 在 Hibernate 中的一对一映射中无法按预期工作

转载 作者:行者123 更新时间:2023-12-02 06:12:59 26 4
gpt4 key购买 nike

在此tutorial ,作者考虑到-

@Entity
@Table
public class Stock implements Serializable {

@Id
@GeneratedValue(strategy = IDENTITY)
@Column
private Integer stockId;

@Column
private String stockCode;

@Column
private String stockName;

@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "stock")
private StockDetail stockDetail;

// getters and setters
}
<小时/>
@Entity
@Table
public class StockDetail implements java.io.Serializable {


@Id
@GeneratedValue(generator = "generator")
@GenericGenerator( name = "generator",
strategy = "foreign",
parameters = @Parameter(name = "property", value = "stock"))
@Column
private Integer stockId;

@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
private Stock stock;
// getters and setters
}

hibernate.cfg.xml 文件具有自动创建如下所示表的条目-

<property name="hbm2ddl.auto">create</property> 
<小时/>
 CREATE TABLE stock
(
stockid serial NOT NULL,
stockcode character varying(255),
stockname character varying(255),
CONSTRAINT stock_pkey PRIMARY KEY (stockid)
)

CREATE TABLE stockdetail
(
stockid integer NOT NULL,
compdesc character varying(255),
compname character varying(255),
listeddate date,
remark character varying(255),
CONSTRAINT stockdetail_pkey PRIMARY KEY (stockid)
)

您会看到stockdetail 表上没有外键约束。为什么?

如果我将@PrimaryKeyJoinColumn更改为@JoinColumn

    @OneToOne(fetch = FetchType.LAZY)
@JoinColumn
private Stock stock;

然后是本例中 hibernate 生成的表 -

CREATE TABLE stockdetail
(
stockid integer NOT NULL,
compdesc character varying(255),
compname character varying(255),
listeddate date,
remark character varying(255),
stock_stockid integer,
CONSTRAINT stockdetail_pkey PRIMARY KEY (stockid),
CONSTRAINT fk9rrwxdqh1fjcoo2usdix4qoiw FOREIGN KEY (stock_stockid)
REFERENCES stock (stockid) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)

哪个如预期那样绝对正确?

请推荐一下?

最佳答案

用此更新您的代码。

@OneToOne(fetch = FetchType.LAZY,optional=false)
@PrimaryKeyJoinColumn
private Stock stock;

引用:https://forum.hibernate.org/viewtopic.php?f=9&t=956345

关于java - @PrimaryKeyJoinColumn 在 Hibernate 中的一对一映射中无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41386223/

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