各位晚安,
我想對具有以下物體及其透視關系的資料庫進行建模:

但是每次我運行 Java 專案在資料庫中創建模型時,我創建的都是這樣的:

還有另一種映射這種關系的方法嗎?我是這樣映射的:
文章物體:
@Entity
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private Boolean featured;
@Column(nullable = false)
private String title;
@Column(nullable = false)
private String url;
@Column(name = "image_url", nullable = false)
private String imageUrl;
@Column(name = "news_site", nullable = false)
private String newsSite;
@Column(nullable = false)
private String summary;
@Column(name = "published_at", nullable = false)
private String publishedAt;
@OneToMany
@JoinColumn(name = "launches_id")
private List<Launches> launches;
@OneToMany
@JoinColumn(name = "events_id")
private List<Events> events;
}
啟動物體
@Entity
public class Launches {
@Id
private String id;
private String provider;
}
事件物體:
@Entity
public class Events {
@Id
private Long id;
private String provider;
}
我想用其他文章中出現的相同啟動器和事件來映射這個 JSON:
{
"id": 4278,
"title": "GAO warns of more JWST delays",
"url": "https://spacenews.com/gao-warns-of-more-jwst-delays/",
"imageUrl": "https://spacenews.com/wp-content/uploads/2019/08/jwst-assembled.jpg",
"newsSite": "SpaceNews",
"summary": "",
"publishedAt": "2020-01-28T23:25:02.000Z",
"updatedAt": "2021-05-18T13:46:00.284Z",
"featured": false,
"launches": [
{
"id": "d0fa4bb2-80ea-4808-af08-7785dde53bf6",
"provider": "Launch Library 2"
}
],
"events": []
},
{
"id": 4304,
"title": "Government watchdog warns of another JWST launch delay",
"url": "https://spaceflightnow.com/2020/01/30/government-watchdog-warns-of-another-jwst-launch-delay/",
"imageUrl": "https://mk0spaceflightnoa02a.kinstacdn.com/wp-content/uploads/2020/01/48936479373_2d8a120c8e_k.jpg",
"newsSite": "Spaceflight Now",
"summary": "",
"publishedAt": "2020-01-30T04:08:00.000Z",
"updatedAt": "2021-05-18T13:46:01.640Z",
"featured": false,
"launches": [
{
"id": "d0fa4bb2-80ea-4808-af08-7785dde53bf6",
"provider": "Launch Library 2"
}
],
"events": []
}
uj5u.com熱心網友回復:
根據您的圖表,它應該是:
@ManyToOne
@JoinColumn(name = "launches_id")
private Launches launches;
@ManyToOne
@JoinColumn(name = "events_id")
private Events events;
...而不是@OneToMany;) (是否有一個“文章”(id=x)具有launchers_id=y 和launchers_id=z?不,反之亦然!:)
...對于@OneToMany,您應該找到“在另一邊”(關系)的連接列。
根據您的 JSON,它是 OneToMany. 但是,我們必須繪制/預期:
@Entity
class Article {
//... id, columns, blah
@OneToMany
@JoinColumn(name = "article_id") // Launches "owns the relationship"/column
private List<Launches> launches;
@OneToMany
@JoinColumn(name = "article_id") // Events...!
private List<Events> events;
}
通常,(當您通過 json 公開資料庫模型時)確保:
沒有“圈子”(雙向關聯)。(
@JsonManagedReference, @JsonBackReference, @JsonIgnoreProperties, ... )不要公開您不想公開的資料。(
@JsonIgnoreProperties, ...)
關于 Hibernate-ManyToOne,請參考https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/
關于 彈簧資料-jpa,最好:
- gs-資料-jpa
- gs-資料休息
- spring-boot-ref,資料-jpa
- 參考檔案,資料-jpa
- 參考檔案,資料休息
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/406471.html
標籤:
