如何在Spring引导中将用户的id插入到产品中



我的用户Id有问题。我有两个模型,用户和产品,它们之间有一个FK(一个用户可以有很多产品(。登录后,我希望用户可以添加新产品,但当我添加新产品时,问题是user_ID列为null,我尝试了很多方法,但无法将user_ID添加到产品中。

这是我的产品

@Entity
@Table(name = "product")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String productName;
private double price;
private String productType;
private String description;
private boolean sold = false;
@ManyToOne
@JoinColumn(name = "userId", insertable = false, updatable = false, referencedColumnName = "id")
private User user;

这是我的用户

@Entity
@Table(name = "user")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotBlank(message = "Please enter your email")
@Email(message = "Enter a valid email address")
private String email;
@NotBlank(message = "Please enter your password")
@Length(min = 6, message = "Password must be at least 6 characters")
private String password;
@NotBlank(message = "Please enter your name")
private String name;
private boolean enable = true;
@OneToMany(mappedBy = "user")
private List<Product> products;

我试着这样添加,但它不起作用

@PostMapping("/mystore")
public String addProduct(Product product) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = (User) authentication.getPrincipal();
System.out.println(user.getId());
product.setUser(user);
productService.save(product);
return "redirect:/mystore";
}

那么,有什么方法可以获得用户的ID并将其添加到产品中吗?

我认为问题是你从authentication.getPrincipal((获取用户。你应该从数据库获取用户,而Spring JPA后面的Hinernate会话将在会话中维护user Entity。因此,使用主体从DB中查询用户,然后将用户设置为产品,然后保存产品

最新更新