gpt4 book ai didi

hibernate - 具有反向外键的单向@OneToOne

转载 作者:行者123 更新时间:2023-12-04 15:42:57 26 4
gpt4 key购买 nike

我们想使用不在主表中但在从表中的外键创建单向@OneToOne映射。通过提供以下Java代码,Hibernate尝试在表product_ID中找到product列,但在productimage中找不到。是否可以使其仅对注释进行修改?

该示例中删除了所有不必要的字段和列。

JPA实体:

@Entity
public class Product {

@Id
@Column(name = "ID", unique = true)
private String id;

// this doesn't work
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "product_ID", nullable = false)
private ProductImage productImage;

// this works, but we want one-to-one
// @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
// @JoinColumn(name = "product_ID", nullable = false)
// private List<ProductImage> productImages;

// getters/setters omitted
}

@Entity
public class ProductImage {

@Id
@Column(name = "ID", unique = true)
private String id;

@Column
@Lob
private Blob data;

// getters/setters omitted
}

数据库表:
CREATE TABLE `product` (
`ID` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
)

CREATE TABLE `productimage` (
`ID` varchar(255) NOT NULL,
`data` longblob NOT NULL,
`product_ID` varchar(255) NOT NULL,
PRIMARY KEY (`ID`),
KEY `FK_123` (`product_ID`),
CONSTRAINT `FK_123` FOREIGN KEY (`product_ID`) REFERENCES `product` (`ID`)
)

最佳答案

JPA实体,更多关于 @PrimaryKeyJoinColumn :

@Entity
public class Product {
@Id
private String id;

@PrimaryKeyJoinColumn
@OneToOne(orhanRemoval = true)
private ProductImage image;
}

@Entity
public class ProductImage {
@Id
private String productId; // this will be foreign key as well as primary

//other properties goes here
}

数据库表:
CREATE TABLE product (
id VARCHAR PRIMARY KEY
);

CREATE TABLE product_image (
product_id VARCHAR PRIMARY KEY REFERENCES product(id)
-- other columns goes here
);

关于hibernate - 具有反向外键的单向@OneToOne,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30851612/

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