I'm auto generating entities within the database which works great using:
spring.jpa.hibernate.ddl-auto=update
Now I need an additional attribute within the association table and I can't figure it out without creating an association entity by hand. The current classes listed below generate an association table without the additional attribute.
The tables I need:
persons:
id
search_requests:
id
search_requests_persons:
person_id
search_request_id
study_id
The classes I currently have (simplified):
@NoArgsConstructor
@RequiredArgsConstructor(staticName = "of")
@Getter
@Setter
@Entity
@EqualsAndHashCode
@Table(name = "persons")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
// The following line is what I would need
// private List<Integer> studyIds;
}
@NoArgsConstructor
@RequiredArgsConstructor(staticName = "of")
@Getter
@Setter
@Entity
@EqualsAndHashCode
@Table(name = "search_requests")
public class SearchRequest {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NonNull
@ManyToMany
private List<Person> persons;
}
I'm using Lombok and Javax Persistence for the annotations.
CodePudding user response:
In order to add additional attributes in your JoinTable
, you could manually create your JoinTable
entity. e.g:
PersonSearchRequest.java
@Entity
@Table(name = "person_search_request)
@Getter
@Setter
@NoArgsConstructor
public class PersonSearchRequest {
@EmbeddedId
private PersonSearchRequestPK id;
// put your additional attribute here, e.g:
private String attribute1;
private Long attribute2;
@ElementCollection
private List<String> attribute3s;
@Embeddable
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public static class PersonSearchRequestPK implements Serializable {
@ManyToOne(fetch = FetchType.LAZY)
private Person person;
@ManyToOne(fetch = FetchType.LAZY)
private SearchRequest searchRequest;
}
}
Person.java
@NoArgsConstructor
@RequiredArgsConstructor(staticName = "of")
@Getter
@Setter
@Entity
@EqualsAndHashCode
@Table(name = "persons")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@OneToMany(mappedBy = "id.person")
private List<PersonSearchRequest> personSearchRequests;
}
SearchRequest.java
@NoArgsConstructor
@RequiredArgsConstructor(staticName = "of")
@Getter
@Setter
@Entity
@EqualsAndHashCode
@Table(name = "search_requests")
public class SearchRequest {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@OneToMany(mappedBy = "id.searchRequest")
private List<PersonSearchRequest> personSearchRequests;
}