为什么我的数据与mysqldb中的错误列关联



我有两个表,它们使用复合键以多对多关系连接:

表1

@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "user_name")
private String userName;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
private String password;
private String authorization;
@OneToMany(
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
@JsonManagedReference
private List<UserProduct> userProducts = new ArrayList<>();
@OneToMany(
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<Orders> orders = new ArrayList<>();

表2

@Entity
@Table(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private int price;
private double mass;
private double alcohol;
private String picture;
private int amount;
@OneToMany(
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<UserProduct> userProducts = new ArrayList<>();
@OneToMany(
mappedBy = "orders",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<OrderProduct> orderProducts = new ArrayList<>();

带有复合密钥的表

@Entity
@Table(name = "user_product")
public class UserProduct {
@EmbeddedId
private UserProductId id;
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("userId")
@JsonBackReference
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("productId")
private Product product;
@Column(name = "amount_of_new_products")
private int amountOfNewProducts;

当我对UserProduct表进行REST调用时,我可以使用以下负载更新产品值:

{
"user": 4,
"product": 2,
"amountOfNewProducts": 32
}

它根据用户id而不是产品id来写入信息。对于这个有效负载,它会这样写入:

{
"id": 3,
"name": "Grimbergen Blanche",
"price": 132,
"mass": 0.33,
"alcohol": 6.0,
"picture": "https://i.imgur.com/qIq1OrC.png",
"amount": 502,
"userProducts": [],
"orderProducts": []
},
{
"id": 4,
"name": "Grimbergen Blonde",
"price": 132,
"mass": 0.33,
"alcohol": 6.7,
"picture": "https://i.imgur.com/OnioHd5.png",
"amount": 435,
"userProducts": [
{
"id": {
"productId": 2,
"userId": 4
},
"product": {
"id": 2,
"name": "Lav Premium",
"price": 73,
"mass": 0.33,
"alcohol": 4.9,
"picture": "https://i.imgur.com/T3gCAOE.png",
"amount": 1862,
"userProducts": [],
"orderProducts": []
},
"amountOfNewProducts": 32
}
],
"orderProducts": []
},

因此,基本上,即使我将2作为产品id传入,信息也会写入id为4的产品中,因为用户id为4。如果能给我任何线索,我会把事情搞砸的,我将不胜感激。

您需要修复Product实体中的mappedBy = "user"。它必须是"product",像这样:

@OneToMany(
mappedBy = "product",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<UserProduct> userProducts = new ArrayList<>();

还要检查您在UserProductId中是否有正确的@JoinColumn(不幸的是,您没有将其代码添加到问题中(。

最新更新