添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'date': it is not exactly10characters long

Ask Question

in my code i have two entities BusDetails and User. The User and the BusDetails has many to many relationship. Whenever i try to book bus, the data is saved in the join table in database but i get this exception:
Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'date'; nested exception is java.lang.IllegalArgumentException: Could not parse date: it is not exactly10characters long]]

User Table:

public class User {
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int u_id;
    @Column
    @NotEmpty(message = "Name cannot be empty")
    private String name;
    @Column
    @NotEmpty(message = "Username cannot be empty")
    private String userName;
    @Column
    @NotEmpty(message = "please enter number")
    @Size(min = 10,max = 10, message = "10 digits required")
    private String number;
    @Column
    @NotEmpty
    @Size(min=8,message = "Minimum 8 characters required")
    private String password;
    @ManyToMany(cascade = CascadeType.MERGE,fetch = FetchType.EAGER)
    @JoinTable(name = "user_role",joinColumns = @JoinColumn(name = "u_id"), inverseJoinColumns = @JoinColumn(name = "r_id"))
    public Set<Role> roles;
    @ManyToMany(cascade = CascadeType.PERSIST,fetch = FetchType.EAGER)
    @JoinTable(name = "user_busdetails", joinColumns = @JoinColumn(name = "u_id") , inverseJoinColumns = @JoinColumn(name = "bus_Id"))
    public Set<BusDetails> bus = new HashSet<BusDetails>();
    //gettersAndSetters

BusDetails:

@Entity
@Component("BusDetails")
public class BusDetails {
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int bus_Id;
    @Column
    public String fromDestination;
    @Column
    public String toDestination;
    @Column
    @DateTimeFormat
    @Temporal(TemporalType.DATE)
    private Date date;
    @Column
    private String travels;
    @Column
    private String bus_Type;
    @Column
    private String seats_Available;
    @Column
    public String fare;
    @Column
    private String departure;
    @ManyToMany(fetch = FetchType.EAGER,mappedBy = "bus")
    @JsonIgnore
    public Set<User> user = new HashSet<User>();
    //gettersAndSetters

BookController:

@PostMapping("/bookbus")
    @ResponseBody
    public BusDetails bookBus(@ModelAttribute BusDetails bus) {
        System.out.println(bus.getDate());
        return busDetail.bookBus(bus);
    @InitBinder     
    public void initBinder(WebDataBinder binder){
         binder.registerCustomEditor(       Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy- 
    MM-dd"), true, 10));   

BookService:

public BusDetails bookBus(BusDetails bus) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentPrincipleName = authentication.getName();
        User user = userRepo.findByUserName(currentPrincipleName);
        user.getBus().add(bus);
        System.out.println(user);
        System.out.println(bus);
        userRepo.save(user);
        return bus;

Because you used @ModelAttribute in the controller means all parameters is pass in String format.

In your case is to format from String to Date.

@Entity
@Component("BusDetails")
public class BusDetails {
    //...
    @Column
    private Date date;
    //setter(can add or modify) should be custom like below :
    public void setDate(String date){
        try {
            this.date = new SimpleDateFormat("yyyy-MM-dd").parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
    // ...getter & setter
                i dont know what change i made, before it was working without the above modification.thanks a lot.
– Pariskrit A. Moktan
                Oct 30, 2019 at 9:39
                @PariskritA.Moktan If you use @RequestBody instead of @ModelAttribute, everything's okay.
– sovannarith cheav
                Oct 30, 2019 at 9:41
    @Bean
    public FormattingConversionService conversionService() {
        DefaultFormattingConversionService conversionService = 
          new DefaultFormattingConversionService(false);
        DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
        registrar.setDateFormatter(DateTimeFormatter.ofPattern("dd.MM.yyyy"));
        registrar.setDateTimeFormatter(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"));
        registrar.registerFormatters(conversionService);
        // other desired formatters
        return conversionService;

First, we create DefaultFormattingConversionService with a false parameter, which means Spring will not register any formatters by default.

And then, we manually register new patterns for date and date-time formats in the DateTimeFormatterRegistrar object.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.