[英]JPA Many-to-Many Relationship with Users Entity Stored in a Different Database
我正在嘗試創建與存儲在不同數據庫中的實體(用戶)的關系,但無法弄清楚如何在 JPA 中執行此操作。
我正在 Spring Boot/JPA 中實施汽車服務。 我創建了一個名為Car
的實體/表。 一輛車可能有多個所有者(用戶),一個用戶可能擁有多輛汽車。 但是, User
表存儲在單獨的用戶服務中。
由於這是一個多對多的關系,我覺得JoinTable
是合適的。 這里的問題是沒有要加入的User
表。 我只需要將用戶的 UUID 存儲在連接表中,因此GET
方法可以獲取給定用戶或給定汽車的所有車主的所有汽車。
這是對Car
實體的嘗試。 刪除ForeignKey
約束允許在連接表中創建條目,而不會由於缺少子表而導致錯誤。
@Data
@Entity
@Table(name = "car")
@EqualsAndHashCode(callSuper = true)
public class Car {
@Id @GeneratedValue private UUID id;
@ManyToMany
@JoinTable(
name = "car_owner",
joinColumns = @JoinColumn(name = "car_id"),
inverseJoinColumns = @JoinColumn(name = "user_id", insertable = false, updatable = false),
foreignKey = @ForeignKey(name="user_id", value = ConstraintMode.NO_CONSTRAINT))
private Set<User> users;
private String model;
private double price;
}
這是User
實體 - JPA JoinTable
所需的實體,但僅用於其 ID:
@Data
@Entity
@EqualsAndHashCode()
public class User {
@Id private UUID id;
@ManyToMany(mappedBy = "users")
@JsonIgnore
private Set<Car> cars;
}
將下面的 model 發送到 JPA 存儲庫save()
方法成功地在連接表中創建汽車和條目:
{
"model": "Ford Model T",
"price": 850.00,
"users": [
{"id": "e048b593-aad9-4285-b3e6-49475ad9bd1d"},
{"id": "1d0f7b1e-bc36-4b99-80a1-8835779598ca"}
]
}
但是,當我嘗試檢索屬於特定用戶 ID 的所有汽車時:
@Query(
value = "select * from car c inner join car_owner co on c.id = co.car_id where co.user_id = :userId",
nativeQuery = true)
List<Car> findByUserId(UUID userId);
我收到以下錯誤:
錯誤:列 user1_.id 不存在已解決 [org.springframework.http.converter.HttpMessageNotWritableException:無法寫入 JSON:無法提取 ResultSet; 嵌套異常是 com.fasterxml.jackson.databind.JsonMappingException: 無法提取 ResultSet (通過參考鏈: java".
如何讀回給定用戶的汽車列表? 我會以錯誤的方式解決這個問題嗎? 我對其他實現持開放態度。
正如@vincendep 提到的,解決方案是刪除User
實體並將Car
實體中的users
屬性替換為以下內容:
@ElementCollection
@CollectionTable(name = "car_owner", joinColumns = @JoinColumn(name = "car_id"))
@Column(name = "user_id")
private Set<UUID> owners;
這仍將使用car_owner
連接表。 可以使用以下 model 創建具有多個用戶的汽車:
{
"model": "Ford Model T",
"price": 850.00,
"owners": [
"32a7967d-8580-418d-b53a-221ed0c52222",
"a708455c-c37c-4712-a7ce-59c9be5a5eb5"
]
}
您可以按用戶 ID 查詢汽車,如下所示(感謝 @vincendep):
@Query(value = "from Car c where :ownerId member of c.owners")
List<Car> findByUserId(UUID ownerId);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.