Spring JPA:添加具有当前用户 ID 的实体作为外键

Spring JPA: Adding an entity with current user ID as foreign key

我正在使用 Thymeleaf HTML 注册表单和简单的 save/update 方法将 save/update 'dish' 对象 mySQL 数据库。 Restaurant Id 是 'dish' 的外键,但使用以下方法将其保存为 'null'、

我想使当前登录的餐厅老板的餐厅 ID 在他们添加菜品时自动保存。

有没有简单的方法来做到这一点?我在 Youtube 上找到的最接近的教程涉及在 Postman 中使用 JSON 请求,我在过去将其适应 HTML 注册表时遇到了问题。

我对所有这一切都很陌生,因此非常感谢任何帮助!

见菜 class:

package com.bron.demoJPA.appuser;
    
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ToString(exclude = "reqlist")
public class Dish {

    @Id
    @SequenceGenerator(name = "dish_sequence", sequenceName = "dish_sequence", allocationSize = 1)

    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dish_sequence")
    @Column(name = "dish_Id")
    private Long dishId;

    @Column(name = "dish_name")
    private String dname;

    @Column(name = "dish_description")
    private String description;

    @Column(name = "dish_price")
    private double price;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "Rest_ID", referencedColumnName = "Rest_ID")
    private AppUser app;

    @ManyToMany(cascade = CascadeType.ALL)

    @JoinTable(name = "dish_requirment_mapping", joinColumns = @JoinColumn(name = "dish_Id", referencedColumnName = "dish_Id"), inverseJoinColumns = @JoinColumn(name = "Require_ID", referencedColumnName = "Require_ID"))
    private List<Requirments> reqlist;

    public void addRequirments(Requirments req) {
        if (reqlist == null)
            reqlist = new ArrayList<>();
        reqlist.add(req);

    }
}

查看 AppUser(餐厅老板)Class

    @Column(name = "Rest_Password")
    private String password;

    @Column(name = "Rest_Email_Address")
    private String email;

    @Enumerated(EnumType.STRING)
    private AppUserRole appUserRole;
    private Boolean locked = false;
    // don't enable user until email verification
    private Boolean enabled = false;

    public AppUser(String restname, String email, String pass, AppUserRole app) {
        this.restaurantName = restname;
        this.email = email;
        this.password = pass;
        this.appUserRole = app;
    }

    public Collection<? extends GrantedAuthority> getAuthorities() {
        SimpleGrantedAuthority authority = new SimpleGrantedAuthority(appUserRole.name());
        return Collections.singletonList(authority);
    }

    @Override
    public String getUsername() {
        return email;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !locked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = true)

    @JoinColumn(name = "openingHourID", referencedColumnName = "OpeningHour_ID")
    private OpeningHour opening;
}

查看控制器 class:

package com.bron.demoJPA.conroller;
@Controller
public class DishController {
//display list of employees
    @Autowired
    private DishService dishService;

    @GetMapping("/dish")
    public String viewHomePage(Model model) {
        model.addAttribute("listDish", dishService.getAllDish());
        return "index";
    }

    @GetMapping("/showNewDishForm")
    public String showNewDishForm(Model model) {
        // Create model attribute to bind form data
        Dish dish = new Dish();
        model.addAttribute("dish", dish);
        return "new_dish";
    }

    @PostMapping("/saveDish")
    public String saveDish(@ModelAttribute("dish") Dish dish) {
        // save dish to database
        dishService.saveDish(dish);
        return "redirect:/dish";
    }



@GetMapping("/showFormForUpdate/{dishId}")
    public String showFormForUpdate(@PathVariable(value = "dishId") long dishId, Model model) {
        // get dish from service
        Dish dish = dishService.getDishByDishId(dishId);

        // set dish as model to pre-populate the form data
        model.addAttribute("dish", dish);
        return "update_dish";

    }

}

查看服务实现

package com.bron.demoJPA.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bron.demoJPA.appuser.Dish;
import com.bron.demoJPA.repository.DishRepository;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishRepository dishRepository;

    @Override
    public List<Dish> getAllDish() {
        return dishRepository.findAll();
    }

    @Override
    public void saveDish(Dish dish) {
        this.dishRepository.save(dish);
    }

    @Override
    public Dish getDishByDishId(long dishId) {
        Optional<Dish> optional = dishRepository.findById(dishId);
        Dish dish = null;
        if (optional.isPresent()) {
            dish = optional.get();
        } else {
            throw new RuntimeException("Dish not found for: " + dishId);
        }
        return dish;
    }
}

查看服务 class

public interface DishService {

    List<Dish> getAllDish();

    void saveDish(Dish dish);

    Dish getDishByDishId(long dishId);

}

在尝试保存之前,您能否确保 Dish 的“app”属性设置正确?

如果它为 null 或者它是 AppUser 的全新实例 class 则在尝试匹配和持久化时它最终为 null 是有道理的。

您好!