我在資料庫中自動生成物體,使用以下方法效果很好:
spring.jpa.hibernate.ddl-auto=update
現在我需要關聯表中的附加屬性,如果不手動創建關聯物體,我無法弄清楚。下面列出的當前類生成沒有附加屬性的關聯表。
我需要的表:
persons:
id
search_requests:
id
search_requests_persons:
person_id
search_request_id
study_id
我目前擁有的課程(簡化):
@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;
}
我使用 Lombok 和 Javax Persistence 作為注釋。
uj5u.com熱心網友回復:
為了在您的 中添加其他屬性JoinTable,您可以手動創建您的JoinTable物體。例如:
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/355889.html
上一篇:Hibernate和PostgreSQL:REPEATABLE_READ和使用@Version注解避免寫傾斜等現象
