0

I need to support with error below:

When I insert data object use RESTFUL API, I have take error throw message from Postman: This is message from Postman

This is data insert from client when I test

This is Class UserEntity

@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class User extends BaseEntity {
    @Column(nullable = false, unique = true, columnDefinition = "varchar(50)")
    private String userName;

    @Column(nullable = false)
    private String password;

    @Column(unique = true, nullable = false)
    private String email;

    @Column(unique = true, nullable = false)
    private String phone;

    @Column
    private String address;

    @Column
    private String fullName;

    @Column
    private LocalDate dateOfBirth;

    @ManyToMany
    @JoinTable(name = "permission",
    joinColumns = @JoinColumn(name = "user_id", nullable = false),
    inverseJoinColumns = @JoinColumn(name = "role_id", nullable = false))
    @JsonIgnore
    private Set<Role> roles = new HashSet<>();

    @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
    @JsonIgnore
    private List<Blog> blogs = new ArrayList<>();
}

This is class UserSaveRequest

@Getter
@Setter
public class UserSaveRequest {
    private long id;
    private String userName;
    private String password;
    private String email;
    private String phone;
    private String address;
    private String fullName;
    private LocalDate dateOfBirth;
    private List<Long> ids;
}

This is method map Object request to Object entity

public User mapToEntity(UserSaveRequest userSaveRequest){
        UserValidate.validate(userSaveRequest);
        String encode = PasswordHasher.hash(userSaveRequest.getPassword());
        User user = new User();
        BeanUtils.refine(userSaveRequest,user,BeanUtils::copyNonNull);
        user.setPassword(encode);
        List<Role> roles = roleRepository.findAllByIdIn(userSaveRequest.getIds());
        user.setRoles(new HashSet<>(roles));

        return user;
    }

This is Class UserController

@RestController // để đánh dấu là API
@RequestMapping("/api")
@Data
public class UserController extends BaseController {

    private final static Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    private final UserService userService;
    private final UserMapper userMapper;
    private final TokenProducer tokenProducer;

    private JwtPayload createPayload(User user){
        JwtPayload jwtPayload = new JwtPayload();
        jwtPayload.setUserName(user.getUserName());
        jwtPayload.setId(user.getId());
        String roles = user.getRoles().stream().map(Role::getName).collect(Collectors.joining(","));

        jwtPayload.setRole(roles);

        return jwtPayload;
    }

    @PostMapping("/user")
    @PreAuthorize("hashAnyRole('ADMIN') OR hashAnyRole('USER') OR hashAnyRole('MANAGER')")
    public ResponseEntity<BaseResponse> save(@RequestBody UserSaveRequest userSaveRequest) {
        userService.save(userSaveRequest, userMapper::mapToEntity);

        return success();
    }
}

This is interface BaseService

public interface BaseService<T, ID>{
    <RQ> void save(RQ req, Function<RQ, T> transform);
}

This is abstract class AbstractServiceImpl

@Data
public abstract class AbstractServiceImpl<T, ID> implements BaseService<T, ID> {

    protected final BaseRepository baseRepository;

    public AbstractServiceImpl(BaseRepository baseRepository){
        this.baseRepository = baseRepository;
    }

    @Override
    public <RQ> void save(RQ req, Function<RQ, T> transform) {
        T t = transform.apply(req);
        baseRepository.save(t);
    }
}

This is UserServiceImpl

@Service
public class UserServiceImpl extends AbstractServiceImpl<User, Long> implements UserService {

    public UserServiceImpl(UserRepository userRepository){
        super(userRepository);
    }
}
TamDV
  • 23
  • 4
  • You might want to look at whether your version of Jackson (dependency of Spring Boot) already supports the java.time API or if you need to add another dependency which contains the converters for `LocalDate` etc. – Thomas Nov 02 '21 at 08:57
  • 1
    Either you are missing a jackson dependency for Java8time or you have configured the `ObjectMapper` yourself (preventing auto configuration) and the java8time module wasn't registered. – M. Deinum Nov 02 '21 at 08:58
  • https://stackoverflow.com/questions/45863678/json-parse-error-can-not-construct-instance-of-java-time-localdate-no-string-a – JCompetence Nov 02 '21 at 09:11

1 Answers1

0

This exception is due to jackson not working correctly, either because it is not in your dependencies1 or the version you're using is not compatible with the LocalDate object. another possibility may be the date format2

1* add this code to your pom.xml :

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
</dependency>

2* you can add a format annotation to your dateOfBirth variable :

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")

and make sure you're respecting the pattern you specified

KASMI G.
  • 116
  • 11
  • 2
    You sholdn't need that dependenc as that is added by default when including the web starter from spring boot. One might need to add the jdk8 date/time support for Jackson (only when using an older version of Spring Boot or Jackson). – M. Deinum Nov 02 '21 at 09:39
  • I try testing it, but problem can't resolve – TamDV Nov 02 '21 at 09:43
  • This is strange ! Have you modified the format ? yyyy-MM-dd in your case – KASMI G. Nov 02 '21 at 09:49
  • @KASMIG. yes i had try modified the format but can't resolve problem it. Can you help me? – TamDV Nov 02 '21 at 09:57
  • I think it is related to your jackson packages. Did you rebuild the project ? Also, there is another way to pass dates without jackson ! You can do it through tables. It would look something like this : "dateOfBirth" : [1995, 10, 12] – KASMI G. Nov 02 '21 at 10:21
  • @KASMIG. I had try to test modified data field datOfBirth, but I can't resolve problem. – TamDV Nov 03 '21 at 04:38
  • I just cheked my code : @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") private LocalDate birthDate; this code works fine when i try to insert : "birthDate" : "01-01-2000" – KASMI G. Nov 03 '21 at 08:58