Issue
i have to map an old database to write a web service. the problem is it use the foreign key as the primerty key. and some non unique row number. then it works as a composite key. here is the class structure
@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;
}
this is the other class
@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;
}
here is the data sample enter image description here
when get te data it will work as expected but when it comes to save its not picking up with foreign key. just check with id which is rownum and throws an exception
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
Solution
Use a mapping like this:
@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)
}
or
@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;
}
Answered By - Christian Beikov
Answer Checked By - Marie Seifert (JavaFixing Admin)