java - JoinColumn Hibernate / API
问题描述
我遇到了以下问题:我想简单地加入表格市场(主要)和电话,但是在使用注释时我遇到了一些问题。
我只是想使用 Comercio.id 作为 Telefone.fk_id 的相应外键,但它无法识别它。我还想问是否需要为这两个类创建一个存储库接口。
编辑。另外,对于这样的示例,POST req 会如何?
商业.java
@Entity
@Table(name = "comercio")
public class Comercio {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String nome;
private String cnpj;
private String endereco;
@OneToMany(targetEntity = Telefone.class , mappedBy = "comercio", fetch = FetchType.LAZY)
private List<Telefone> telefones;
private String email;
Telefone.java
@Entity
@Table(name = "telefone")
public class Telefone {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long telefone_id;
@ManyToOne
@JoinColumn(name="fk_id", referencedColumnName = "id")
private Comercio comercio;
private String telefone;
我得到的答案:
{
"nome" : "Americanas",
"cnpj" : "000",
"endereco" : "SQN 112",
"telefones" : [ ],
"email" : "contato@americanas.com",
"comercio_id" : 1
}
安慰:
Hibernate: select comercio0_.id as id1_0_, comercio0_.cnpj as cnpj2_0_, comercio0_.email as email3_0_, comercio0_.endereco as endereco4_0_, comercio0_.nome as nome5_0_ from comercio comercio0_
Hibernate: select telefones0_.fk_id as fk_id3_1_0_, telefones0_.telefone_id as telefone1_1_0_, telefones0_.telefone_id as telefone1_1_1_, telefones0_.fk_id as fk_id3_1_1_, telefones0_.telefone as telefone2_1_1_ from telefone telefones0_ where telefones0_.fk_id=**?**
感谢任何帮助。
解决方案
我建议电话本身不是一个实体:你永远不会想要查询电话,它只作为商业的一部分存在。
然后它可能是一个Embeddable
而不是一个实体,但是因为它只有一个属性 - 数字 - 然后您可以简化为下面并将其映射为字符串的集合。那么就不需要Telefone
上课了。
@Entity
@Table(name = "comercio")
public class Comercio {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String nome;
private String cnpj;
private String endereco;
@ELementCollection
@CollectionTable(name = "comercio_telefone",
joinColumns=@JoinColumn(name="comercio_id"))
private List<String> telefones;
private String email;
}
推荐阅读
- ssis - 一一加载SSIS多个文件
- c++ - 如何检查模板参数是否是 C++ 中的特定类型
- c# - NullReferenceException:对象引用未设置为统一 c# 中的对象实例
- python - 如何制作一个不和谐的机器人,以便它可以将通知从网站发送到某个频道 Python
- unit-testing - 如何向 CKEditor 自定义插件添加单元测试
- angular - 问题:在 [attr.aria-label] 中插入条件
- reactjs - Reactjs 中的 Crud 更新操作不起作用
- python - 从 google book api 获取缩略图到 python 变量
- reactjs - 您可以将 React useState 状态对象传递给使用 Tailwind 和 twin.macro 的样式化组件吗?
- c# - 尝试修复此 dataGridView 列 Autosizemode 问题