Spring JPA关节表

vhmi4jdf  于 2022-10-04  发布在  Spring
关注(0)|答案(1)|浏览(136)

我必须Map一个旧数据库来编写Web服务。问题是它使用外键作为主键。和一些非唯一的行号。然后,它将作为组合键工作。下面是类结构

@Entity
@Table(name = "AD_CLIENT")
public class Client {
    @Id
    @Column(name = "CLIENT_CODE")
    private String clientCode;
    @Column(name = "CLIENT_NAME")
    private String fullName;

    @OneToMany(mappedBy = "client",fetch = FetchType.LAZY)
    @JsonIgnore
    List<ClientTelephone> clientTelephones;
}

这是另一个班级

@Entity
@Table(name="AD_CLIENT_TELEPHONE")
public class ClientTelephone {
    @Id
    @Column(name = "ROW_NUMBER")
    private int rownum;
    @Column(name = "TEL_NO")
    private String telephone;
    @Column(name = "TEL_TYPE")
    private String telType;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "CLIENT_CODE")
    @JsonIgnore 
    private Client client;
}

以下是数据示例enter image description here

当获取TE数据时,它会正常工作,但当涉及到保存时,它不会用外键拾取。只需使用为rownum的id进行检查并抛出异常

Hibernate: select c1_0.row_number,c1_0.client_code,c1_0.tel_type,c1_0.tel_no from ad_client_telephone c1_0 where c1_0.row_number=?
2022-09-23T15:32:37.051+05:30  INFO 56164 --- [nio-8080-exec-5] o.h.e.internal.DefaultLoadEventListener  : HHH000327: Error performing load command

org.hibernate.HibernateException: Duplicate row was found and `ASSERT` was specified
uqdfh47h

uqdfh47h1#

使用如下所示的Map:

@Entity
@Table(name="AD_CLIENT_TELEPHONE")
public class ClientTelephone {
    @Id
    @Column(name = "ROW_NUMBER")
    private int rownum;
    @Id
    @JoinColumn(name = "CLIENT_CODE")
    @JsonIgnore 
    private Client client;
    @Column(name = "TEL_NO")
    private String telephone;
    @Column(name = "TEL_TYPE")
    private String telType;
    @ManyToOne(fetch = FetchType.LAZY)
}

@Entity
@Table(name = "AD_CLIENT")
public class Client {
    @Id
    @Column(name = "CLIENT_CODE")
    private String clientCode;
    @Column(name = "CLIENT_NAME")
    private String fullName;

    @ElementCollection
    @CollectionTable(name = "AD_CLIENT_TELEPHONE")
    @OrderColumn(name = "ROW_NUMBER")
    @JsonIgnore
    List<ClientTelephone> clientTelephones;
}
@Embeddable
public class ClientTelephone {
    @Column(name = "TEL_NO")
    private String telephone;
    @Column(name = "TEL_TYPE")
    private String telType;
}

相关问题