如何通过JPA加入这3个表

时间:2019-05-07 09:30:21

标签: java postgresql jpa

我想加入这3个表。 enter image description here

在这里您看到我的Person实体

    @Entity
@Table(name = "Person", schema = "public")

public class PatientEntity {

@Id
@Column(name = "id")
private Long id;
@Column(name = "lastname")
private String name;

@OneToMany
@JoinTable(name = "person_contact", joinColumns = { @JoinColumn(name = "person_id") }, inverseJoinColumns = { @JoinColumn(referencedColumnName = "id") })
@Column(name = "contact")
private Set<ContactEntity> contacts;
//Getter Setters

这是我的联系实体:

@Entity
@Table(name="contact",schema="public")
public class ContactEntity {
    @Id
    @Column(name="id")
    private Long id;
    @Column(name="phone")
    private String phone;
//Getter Setters

我只是使用带有Spring JPARepository的findById从表中读取了Persons,但是没有映射Contact。我的HTTP请求期间没有错误,但是没有Contact,而是null,并且此错误消息: com.sun.jdi.InvocationException发生了调用方法。

业务案例是,每个人都可以有一个或多个联系人。是否可以使用JPA批注进行制作,还是需要我自己使用JPQL进行映射?还是应该为中间表创建一个实体? (person_contact)

该数据库是PostgreSQL数据库。 日志中也有此通知:

ERROR: column contacts0_.contacts_id does not exist
  Perhaps you meant to reference the column "contacts0_.contact_id".
  Position: 306

1 个答案:

答案 0 :(得分:2)

您的@JoinTable的{​​{1}}规范不正确,并与以下ddl相对应。

@JoinColumn

要映射您的数据库结构,请使用以下命令(注意删除了create table person_contact (person_id bigint not null, contacts_id bigint not null, primary key (person_id, contacts_id)) 注释)

@Column

我还建议您阅读https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/并重新考虑没有连接表的数据库结构(取决于您的负载和进行此数据库更改的工作量)