【发布时间】:2020-01-25 04:01:32
【问题描述】:
假设我有两个数据库表,Product 和 ProductDetails。
create table Product
{
product_id int not null,
product_name varchar(100) not null,
PRIMARY KEY (product_id)
}
create table ProductDetails
{
detail_id int not null,
product_id int not null,
description varchar(100) not null,
PRIMARY KEY (detail_id,product_id),
FOREIGN KEY (product_id) REFERENCES Product(product_id)
}
每个产品可以有多个产品详情条目,但每个产品详情只能属于一个产品。在 SQL 中,我希望能够检索每个产品详细信息,但也可以使用产品名称,我会使用 join 语句来实现。
select p.product_id,pd.detail_id,p.product_name,pd.description
from Product p join ProductDetails pd on p.product_id=pd.product_id
现在我需要在 Spring data JPA 表单中包含这个概念。我目前的理解如下:
@Table(name = "Product")
public class ProductClass
{
private int productID;
private String productName;
}
@Table(name = "ProductDetails")
public class ProductDetailsClass
{
private int detailID;
private int productID;
// this is the part I don't know how to set. @OneToMany? @ManyToOne? @JoinTable? @JoinColumn?
private String productName;
private String description;
}
(我没有包含任何属性,例如@Id 以保持代码最少)
我需要写什么才能让private String productName; 工作?
我对@JoinTable 和@OneToMany 和其他属性的研究让我更加困惑。
附:这是我继承的遗留 Java 程序。 private String productName; 部分不在原始代码中,但现在我需要 ProductDetails 类才能使 productName 可用。
附言在尝试任何事情和部署之前,我想清楚地了解我在做什么。这是一个部署到生产环境的遗留程序,据我了解,这里的任何代码更改也会改变数据库结构,再多的钱也不足以让我想恢复 Java 程序、Spring 框架、Apache如果发生任何灾难性事件,服务器和 MySQL 数据库将恢复正常工作。另外我真的没有开发环境来测试这个。帮助...
【问题讨论】:
标签: java join spring-data-jpa