Vaadin:DateField 的值在转换后为空

Vaadin: value from DateField is null after conversion

我遇到了无法将 DateField 中输入的日期保存到数据库的问题。我正在使用 Hibernate 作为 ORM 框架,并且有一个包含 java.sql.Date 字段的 Order 实体。但据我所知,DateField 仅适用于 LocalDate/LocalDateTime。因此,为了绑定这些字段,我创建了 Converter class。问题是 Converter 收到了一个空值,这就是我得到堆栈跟踪的原因,但是这个问题在这个线程中得到了解决: 非常感谢@Cashbee。 修复转换器 class 后,值已正确保存到数据库中。但过了一段时间,情况又重复了

目前,当我点击 save() 按钮时,转换器会收到正确的值:

然而,绑定后该值为空:

你能帮我找到解决办法吗

VAADIN v.8.6.2

实体(简化):

/*imports...*/
import java.sql.Date;

@Entity
@DynamicInsert
@DynamicUpdate
@Table(name = "Orders")
public class Order{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "OrderID", nullable = false)
    private Long orderID;

    @Column(name = "CreationDate", nullable = false)
    private Date creationDate;

public Date getCreationDate() { return creationDate; }

public void setCreationDate(Date creationDate) { this.creationDate = creationDate; }

//... other getters & setters

}

转换器:

import com.vaadin.data.Converter;
import com.vaadin.data.Result;
import com.vaadin.data.ValueContext;

import java.sql.Date;
import java.time.LocalDate;

public class SqlDateToLocalDateConverter implements Converter<LocalDate, java.sql.Date> {

    @Override
    public Result<java.sql.Date> convertToModel(LocalDate value, ValueContext context) {
        if (value == null) {
            return Result.ok(null);
        }
        return Result.ok( java.sql.Date.valueOf(value) );
    }

    @Override
    public LocalDate convertToPresentation(java.sql.Date value, ValueContext context) {
        if (value == null) {
            return LocalDate.now();
        }
        return value.toLocalDate();
    }
}

Class 绑定(简化):

public class AddOrderModalView extends Window {

    private OrderService orderService = new OrderService();
    private Order order = new Order();
    Binder<Order> binder = new Binder<>(Order.class);

    private ChangeHandler changeHandler = new ChangeHandler() {
        @Override
        public void onChange() { }
    };

    private FormLayout formLayout = new FormLayout();
    private DateField creationDate = new DateField("Creation Date");
    private Button save = new Button("Save");
    private Button cancel = new Button("Cancel");


    public AddOrderModalView() {

        VerticalLayout subContent = new VerticalLayout();
        subContent.setSizeFull();

        HorizontalLayout actions = new HorizontalLayout();
        actions.addComponents(save, cancel);

        creationDate.setDateFormat("yyyy-MM-dd HH:mm:ss");

        formLayout.addComponents(creationDate, actions);

        subContent.addComponent(formLayout);
        setContent(subContent);

        save.addClickListener(e -> save());
        cancel.addClickListener(e -> close());

        bindingFields();

        setModal(true);
    }

    private void bindingFields() {
        binder.forField(this.creationDate)
                .withConverter(new SqlDateToLocalDateConverter())   //Converter java.sql.Data -> LocalDate and vise versa
                .bind(Order::getCreationDate, Order::setCreationDate);

        // ...other fields

       //binder.bindInstanceFields(this);

       binder.setBean(order);
    }

    public interface ChangeHandler { void onChange(); }


    private void save() {
        if (binder.validate().isOk()) {
            orderService.persist(order);
            close();
            changeHandler.onChange();
        }
    }
}

堆栈跟踪:

org.hibernate.PropertyValueException: not-null property references a null or transient value : com.haulmont.testtask.model.Order.creationDate
        at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:108)
        at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:56)
        at org.hibernate.action.internal.AbstractEntityInsertAction.nullifyTransientReferencesIfNotAlready(AbstractEntityInsertAction.java:115)
        at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:69)
        at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645)
        at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282)
        at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)
        at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317)
        at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:359)
        at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:292)
        at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:200)
        at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:131)
        at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
        at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
        at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
        at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
        at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
        at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:709)
        at org.hibernate.internal.SessionImpl.save(SessionImpl.java:701)
        at org.hibernate.internal.SessionImpl.save(SessionImpl.java:696)
        at com.haulmont.testtask.dao.OrderDao.persist(OrderDao.java:67)
        at com.haulmont.testtask.service.OrderService.persist(OrderService.java:18)
        at com.haulmont.testtask.ui.AddOrderModalView.save(AddOrderModalView.java:189)
        at com.haulmont.testtask.ui.AddOrderModalView.lambda$new446b05(AddOrderModalView.java:113)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:499)
        at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:273)
        at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:237)
        at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:1014)
        at com.vaadin.ui.Button.fireClick(Button.java:384)
        at com.vaadin.ui.Button.click(Button.java:57)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:155)
        at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:116)
        at com.vaadin.server.communication.ServerRpcHandler.handleInvocation(ServerRpcHandler.java:445)
        at com.vaadin.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:410)
        at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:274)
        at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:90)
        at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:40)
        at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1601)
        at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:445)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
        at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:845)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1689)
        at org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter.doFilter(WebSocketUpgradeFilter.java:225)
        at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
        at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
        at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
        at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
        at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1174)
        at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
        at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1106)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
        at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213)
        at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:119)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
        at org.eclipse.jetty.server.Server.handle(Server.java:524)
        at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:319)
        at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:253)
        at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
        at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
        at org.eclipse.jetty.io.SelectChannelEndPoint.run(SelectChannelEndPoint.java:93)
        at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
        at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
        at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
        at org.eclipse.jetty.util.thread.QueuedThreadPool.run(QueuedThreadPool.java:589)
        at java.lang.Thread.run(Thread.java:748)

我重新创建了您的设置,只有细微差别(使用 Vaadin 8.4.3 并且没有尝试保存到数据库)并且对我来说它有效。

不过,我知道你的问题出在哪里:

在您的 Converter 方法 convertToPresentation() 中,您 return LocalDate.now() 如果 java.sql.Date 值为 null
这将在 DateField 中显示今天的值,尽管 order.creationDate 的值仍然是 null

仅当您从未通过 DateField 手动更改 creationDate 的值时才会出现该错误。一旦您在那里设置了新值,您的 order.creationDate 值将成功更新并且不再为空。

为防止这种情况发生,请将 convertToPresentation() 的 return 值更改为 null,如果值为 null

@Override
public LocalDate convertToPresentation(java.sql.Date value, ValueContext context) {
    if (value == null) {
        //return LocalDate.now();
        return null;
    }
    return value.toLocalDate();
}

如果您希望将 creationDate 值最初设置为今天,您可以在调用 binder.setBean(order);

之前在绑定视图中执行此操作
order.setCreationDate(new java.sql.Date(Calendar.getInstance().getTime().getTime());); //not sure how, I just googled it
binder.setBean(order);