当前位置: 首页 > 知识库问答 >
问题:

无法将java.lang.String类型的属性值转换为属性date所需的类型java.util.Date:它不完全是10个字符长

常睿范
2023-03-14

在我的代码中,我有两个实体BusDetails和User。用户和总线细节具有多对多关系。每当我尝试预订总线时,数据都保存在数据库的连接表中,但我遇到了以下异常:
无法转换“java”类型的属性值。lang.String“to required type”java。util。“日期”表示财产“日期”;嵌套的异常是java。lang.IllegalArgumentException:无法分析日期:它不是精确的10个字符长]]

用户表:

public class User {


    @Id
    @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

总线详细信息:

@Entity
@Component("BusDetails")
public class BusDetails {

    @Id
    @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

图书管理员:

@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));   
    }

图书服务:

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;


    }

共有2个答案

秦天宇
2023-03-14

在应用程序级别转换日期参数

@Configuration
class DateTimeConfig {
    @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;
    }
}

首先,我们使用false参数创建DefaultFormatingConversionService,这意味着Spring默认不会注册任何格式化程序。

然后,我们在DateTimeformatterRegistrator对象中手动注册日期和日期时间格式的新模式。

穆英飙
2023-03-14

因为您在控制器中使用了@modeldattribute,这意味着所有参数都是以字符串格式传递的。

在您的例子中,格式是从字符串到日期。

@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
}
 类似资料: