gpt4 book ai didi

java - 使用 Principal REST hibernate @OneToOne 映射

转载 作者:行者123 更新时间:2023-11-28 23:14:28 24 4
gpt4 key购买 nike

解决方案:我解决了它,这是新的 RestUser.java,如果它可以帮助将来的任何人

@RequestMapping(value="/rate", method=RequestMethod.POST)
public ResponseEntity rate(@RequestBody Rating rating, Principal principal){

User user = userService.findByUsername(principal.getName());
Rating ratingAVG = ratingService.findOne(user.getId());
ratingAVG.setFood(rating.getFood());
ratingAVG.setService(rating.getService());
user.setRating(ratingAVG);
ratingAVG.setUser(user);
userService.save(user);

return new ResponseEntity("Rated!", HttpStatus.OK);
}

问题

我在插入/更新具有外键的对象时遇到问题。我有一个名为 Rating 的表,看起来像这样。我想添加一个唯一的 Rating 对象,该对象使用 principal.getName() 获取当前 user_id。我正在使用高级 REST 客户端对其进行测试并且我已经登录了

+------------------------------------------------+
| Rating |
+------------------------------------------------+
| id | food | service | user_id |
+----+-------------+----------------+------------+
| 1 | 5 | 5 | 1 |
+----+-------------+----------------+------------+

用户.java

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="Id", nullable=false, updatable=false)
private long id;

private String username;
private String password;
private String firstName;
private String lastName;

@OneToOne(cascade=CascadeType.ALL, mappedBy="user")
@JoinColumn(name="user_id", unique=true)
private Rating rating;

评分.java

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

private int food;
private int service;

@OneToOne(cascade = CascadeType.ALL)
@JsonIgnore
private User user;

RatingServiceimpl.java

@Service
public class RatingServiceImpl implements RatingService {

@Autowired
private RatingRepository ratingRepository;

@Override
public Rating save(Rating rating) {
return ratingRepository.save(rating);
}

}

用户休息.java

@RestController
@RequestMapping("/user")
public class UserRest {

@Autowired
UserService userService;

@Autowired
RatingService ratingService;


@RequestMapping(value="/rate", method=RequestMethod.POST)
public ResponseEntity rate(@RequestBody Rating rating, Principal principal){

User user = userService.findByUsername(principal.getName());
user.setRating(rating);
rating.setUser(user);
userService.save(user);

return new ResponseEntity("Rated!", HttpStatus.OK);
}

}

这就是我得到的,它添加了一个新对象,而我只希望它更新现有对象。

MySQL Browser Screen

谢谢!

最佳答案

看起来您正在使用我们设置的用户保存评分。我没有看到任何“@Transaction”注释,所以我假设您的交易在“RatingRepository”内,这意味着您的交易将在您为用户设置评级之前提交。

尝试在调用保存之前将用户设置为评级。

关于java - 使用 Principal REST hibernate @OneToOne 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44484735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com