解决方案:我解决了它,这是新的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对象,该对象将当前user_id与principal.getName()
一起使用。我正在使用高级REST客户端来测试它并且已经登录
+------------------------------------------------+
| Rating |
+------------------------------------------------+
| id | food | service | user_id |
+----+-------------+----------------+------------+
| 1 | 5 | 5 | 1 |
+----+-------------+----------------+------------+
User.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;
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);
}
}
UserRest.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);
}
}
这就是我得到的,它添加了一个新对象,而我只是想让它更新现有的对象。
谢谢!
答案 0 :(得分:1)
看起来您正在通过我们设置用户来保存评级。我没有看到任何'@Transaction'注释,因此我假设您的交易在'RatingRepository'内,这意味着您在将评级设置为用户之前将提交您的交易。
尝试在调用save之前将用户设置为等级。