Jus*_*tin 8 java spring hibernate jpa spring-data
我想在 2 个实体、消费者和政策之间建立一对多关系。一个消费者应该有几个政策。
这是我想要的消费者 JSON 对象的示例:
{
id : 1,
name : "Peter",
endpoint: "123.456.778",
policies: [
{
id : 1,
name: "policy 01"
},
{
id : 2,
name: "policy 02"
}
]
}
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止:
政策实体
@Entity
public class Policy {
@Id
@GeneratedValue
@Column(name = "id")
private Integer id;
@Column(name = "name")
private String name;
//getters and setters
}
Run Code Online (Sandbox Code Playgroud)
消费者实体
@Entity
public class Consumer {
@Id
@GeneratedValue
@Column(name = "consumer_id")
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "endpoint")
private String endpoint;
@OneToMany
@JoinColumn(??)
private List<Policy> policies;
//getters and setters
}
Run Code Online (Sandbox Code Playgroud)
我认为这并不难,但我现在尝试了几个小时,但无法完成。我是 Spring 的新手,所以如果有人能够帮助我,我将非常感激!
@Entity
public class Consumer {
@OneToMany(mappedBy = "consumer")
private List<Policy> policies;
}
@Entity
public class Policy {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn("consumer_id")
private Consumer consumer;
}
Run Code Online (Sandbox Code Playgroud)
fetch = FetchType.LAZY 不是必需的,而是可取的。
我在这里提供了一些基础知识
什么是@JoinColumn 以及它在 Hibernate 中的使用方式
如果你想要一个Policy没有Consumer:
您可以使用连接表
@Entity
public class Consumer {
@OneToMany
private List<Policy> policies;
}
@Entity
public class Policy {
}
Run Code Online (Sandbox Code Playgroud)
单向关系(Policy表会有consumer_id列,但Policy类没有Consumer)
@Entity
public class Consumer {
@OneToMany
@JoinColumn("consumer_id")
private List<Policy> policies;
}
@Entity
public class Policy {
}
Run Code Online (Sandbox Code Playgroud)
另外,请记住,如果您想将 aPolicy作为表格数据(来自字典),您将需要@ManyToMany.
| 归档时间: |
|
| 查看次数: |
12817 次 |
| 最近记录: |