![](/img/trans.png)
[英]Spring JPA: How to insert data to join many tables with @ManytoMany relationship
[英]JPA Insert Into Large ManyToMany
我有這 2 個實體(商店和產品)我已經有了產品,我想將其分配給商店,問題是商店可能有數千種產品並且要“插入”我必須擁有這些產品在內存中,然后將商店與產品集一起保存。 這讓我有一個 StackOverflowError 並且效率非常低。
有沒有辦法做這樣的事情?
insert into product_store (product_id, store_id) VALUES (:productIds, :storeId)
實體:
@Entity
@Table(name = "stores")
data class Store(@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,
@Column
val name: String,
@Column
val street: String,
@Column
val streetNumber: String,
@Column
val postalCode: Int,
@Column
val city: String,
@Column
val state: String,
@Column
val latitude: Double,
@Column
val longitude: Double,
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "product_store",
joinColumns = [JoinColumn(name = "store_id")],
inverseJoinColumns = [JoinColumn(name = "product_id")])
val products: Set<Product>
) : DateAudit()
產品實體:
@Entity
@Table(name = "products")
data class Product(@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,
@Column(nullable = false)
val codeBar: String,
@Column(nullable = false)
val name: String,
@Column(columnDefinition = "text")
val description: String,
@Column(columnDefinition = "text")
val ingredients: String?,
val picture: String,
@OneToMany(fetch = FetchType.EAGER, cascade = [CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH])
val nutriments: Set<Nutriment>,
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "brand_id")
val brand: Brand,
@ManyToMany(fetch = FetchType.EAGER, cascade = [CascadeType.MERGE])
@JoinTable(name = "product_category",
joinColumns = [JoinColumn(name = "product_id")],
inverseJoinColumns = [JoinColumn(name = "category_id")])
val categories: Set<Category>
) : DateAudit()
像這樣固定
@Modifying
@Query("INSERT INTO product_store (product_id, store_id) " +
"(SELECT p.id, s.id FROM products p, stores s WHERE p.market_id IN (:productMarketIds) AND s.id = :storeId)", nativeQuery = true)
fun saveProductsToStoreByProductMarketIds(storeId: Long, productMarketIds: Set<String>)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.