When you have user relation to entity and need to add user to newly created record, follow this way.
Entity is i.e. Order.
In OrderResource.java add:@Inject private UserRepository UserRepository;
Somewhere at the end add:
public String getCurrentUserLogin() { org.springframework.security.core.context.SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); String login = null; if (authentication != null) if (authentication.getPrincipal() instanceof UserDetails) login = ((UserDetails) authentication.getPrincipal()).getUsername(); else if (authentication.getPrincipal() instanceof String) login = (String) authentication.getPrincipal(); return login;
}
In the POST section, before *OrderRepository.save* add:
User user=new User(); user=UserRepository.findOneByLogin(getCurrentUserLogin()).get(); Order.setUser(user);
Brak komentarzy:
Prześlij komentarz