每當用戶添加優惠時,我都會嘗試將所有者(用戶)與優惠(汽車)映射。像下面這樣的設定 user_id 始終為空。我錯過了什么?我認為這與控制器有關。映射對我來說似乎沒問題,但我可能錯了。所有者是登錄并添加報價的人,因此應該通過他的 id 映射。
編輯我發現我的@AuthenticationPrincipal 身份驗證身份始終為空,即使只有經過身份驗證的用戶才能訪問 POST /api/cars 端點。似乎違反直覺
汽車控制器
@Controller
public class CarController {
@Autowired
private CarService carService;
@Autowired
UserRepository userRepository;
@GetMapping("/api/cars")
public String getCars(Model model) {
model.addAttribute("cars", carService.getAllCars());
return "cars";
}
@GetMapping("/api/cars/new")
public String createNewCarOfferForm(Model model) {
Car car = new Car();
model.addAttribute("car", car);
return "createNewOfferForm";
}
@PostMapping("/api/cars")
public String saveCar(@ModelAttribute("car") Car car, @AuthenticationPrincipal Authentication auth) {
User customUser = (User)auth;
car.setOwner(customUser);
carService.saveCar(car);
return "redirect:/api/cars";
}
@GetMapping("/api/cars/view/{id}")
public String viewOffer(@PathVariable Long id, Model model) {
model.addAttribute("car", carService.getCarById(id));
return "viewOffer";
}
}
用戶物體
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String roles = "ROLE_USER";
@OneToMany(mappedBy = "owner")
private Set<Car> cars = new HashSet<>();
public User() {
super();
}
public User(String username, String password, String roles) {
super();
this.username = username;
this.password = password;
this.roles = roles;
//GETTERS SETTERS
汽車物體
@Entity
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String carPhotoUrl;
private String carTitle;
private double price;
private int yearModel;
private int mileage;
private String engineType;
private float engineCapacity;
private int enginePower;
private String gearboxType;
private String driveType;
private String colour;
private Boolean isDamaged;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="user_id", referencedColumnName = "id")
private User owner;
public Car() {
super();
}
public Car(String carPhotoUrl, String carTitle, double price, int yearModel, int mileage, String engineType,
float engineCapacity, int enginePower, String gearboxType, String driveType, String colour,
Boolean isDamaged) {
super();
this.carPhotoUrl = carPhotoUrl;
this.carTitle = carTitle;
this.price = price;
this.yearModel = yearModel;
this.mileage = mileage;
this.engineType = engineType;
this.engineCapacity = engineCapacity;
this.enginePower = enginePower;
this.gearboxType = gearboxType;
this.driveType = driveType;
this.colour = colour;
this.isDamaged = isDamaged;
}
//GETTERS SETTERS
用戶存盤庫
public interface UserRepository extends JpaRepository<User, Long>
{
Optional<User> findByUsername(String username);
Optional<User> findById(Long id);
}
用戶詳情服務
public class UserDetailsService implements UserDetails{
private String username;
private String password;
private List<GrantedAuthority> authorities;
public UserDetailsService() {
super();
}
public UserDetailsService(User user){
this.username=user.getUsername();
this.password=user.getPassword();
this.authorities = Arrays.stream(user.getRoles().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
uj5u.com熱心網友回復:
我相信您需要在所有者“cascade=CascadeType.ALL”中提及級聯型別,這實質上意味著用戶(所有者)發生的任何更改也必須級聯到 Car。
如果我們保存一個用戶(所有者),那么所有關聯的汽車也將保存到資料庫中。如果您洗掉用戶(所有者),則與該用戶(所有者)關聯的所有汽車也將被洗掉。夠簡單!
uj5u.com熱心網友回復:
我修好了,但我花了一些時間。現在這是添加汽車的端點(所以沒有@AuthenticationPrincipal)
@PostMapping("/api/cars/addCar")
public String saveCar(@ModelAttribute("car") Car car, Principal
principal) {
User user = userService.getUserByName(principal.getName());
car.setOwner(user);
carService.saveCar(car);
return "redirect:/api/cars";
}
我敢打賭這不是一個干凈的解決方案。我已將 UserRepository 的回傳型別從 Optional 更改為 User。我認為這會在未來帶來更多的問題。但現在它有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479459.html
上一篇:restapiwithspring:基于另一個物體創建一個新物體
下一篇:Spring依賴關系還是默認值?
