У меня есть сущность по имени Пользователь с несколькими связями с другими сущностями. Ну, я создал DTO для этой сущности и Mapper, используя MapStruct.
Запрос get работает нормально, но при попытке сделать сообщение возвращает 500.
Пользователь:
@Entity(name="user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
private String password;
private String email;
private Boolean admin;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Account> accounts;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Budget budget;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Transaction> transactions;
Пользователь DTO:
public class UserDto {
private Long id;
private String username;
private String password;
private String email;
private Boolean admin;
private List<AccountDto> accounts;
private BudgetDto budgetDto;
private List<TransactionDto> transactions;
public UserDto() {
}
public UserDto(String username, String password,
String email, Boolean admin, List<AccountDto> accounts, BudgetDto budgetDto, List<TransactionDto> transactions) {
this.username = username;
this.password = password;
this.email = email;
this.admin = admin;
this.accounts = accounts;
this.budgetDto = budgetDto;
this.transactions = transactions;
}
Пользовательский маппер:
@Mapper(componentModel = "spring")
public abstract class UserMapper {
@Autowired
EntityManager entityManager;
public abstract UserDto toDto(User user);
@Mapping(target="accounts", ignore=true)
@Mapping(target="budget", ignore=true)
@Mapping(target="transactions", ignore=true)
public abstract User toEntity(UserDto userDto);
@AfterMapping
void afterToEntity(@MappingTarget User user, UserDto userDto){
List<AccountDto> accountDtoList = userDto.getAccounts();
List<Long> accountIds = accountDtoList.stream().map(AccountDto::getId).collect(Collectors.toList());
List<Account> accounts = accountIds
.stream()
.map(id -> entityManager.find(Account.class, id))
.collect(Collectors.toList());
user.setAccounts(accounts);
Long id = userDto.getBudgetDto().getId();
Budget budget = entityManager.find(Budget.class, id);
user.setBudget(budget);
List<TransactionDto> transactionDtoList = userDto.getTransactions();
List<Long> transactionIds = transactionDtoList.stream().map(TransactionDto::getId).collect(Collectors.toList());
List<Transaction> transactions = transactionIds
.stream()
.map(t_id -> entityManager.find(Transaction.class, t_id))
.collect(Collectors.toList());
user.setTransactions(transactions);
}
}
Пользовательский контроллер:
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:4200")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private UserMapper userMapper;
@GetMapping("/test")
public String hello(){
return "Hello";
}
@GetMapping("/list")
public List<UserDto> getAll() {
List<User> categories = userService.findAll();
return categories.stream()
.map(userMapper::toDto)
.collect(Collectors.toList());
}
@PostMapping("/create")
public UserDto createUser(@Valid @RequestBody UserDto userDto) {
User user = userMapper.toEntity(userDto);
User userResult = userService.save(user);
return userMapper.toDto(userResult);
}
Я попытался сделать запрос с:
{
"admin": "true",
"email": "x@gmail.com",
"пароль": "х",
"имя пользователя": "х"
}
И он возвращает:
{
«метка времени»: «2019-06-02T14: 15: 51,825 + 0000»,
«статус»: 500,
«ошибка»: «Внутренняя ошибка сервера»,
"message": "Нет доступных сообщений",
"trace": "java.lang.NullPointerException