Reputation: 14126
In this tutorial, the author takes into consideration-
@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
}
with the hibernate.cfg.xml file having the entry to auto create the tables which are shown below-
<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)
)
and
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)
)
You see that there is no foreign key constraint on stockdetail table. Why?
If I change @PrimaryKeyJoinColumn to @JoinColumn
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn
private Stock stock;
then the table generated by hibernate in this case -
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
)
which is absolutely correct as expected?
Please suggest?
Upvotes: 3
Views: 842
Reputation: 237
Update your code with this.
@OneToOne(fetch = FetchType.LAZY,optional=false)
@PrimaryKeyJoinColumn
private Stock stock;
Reference: https://forum.hibernate.org/viewtopic.php?f=9&t=956345
Upvotes: 1