java - 如何在 Vaadin 中处理包含 @Id @GenerateVaule 的 bean?

标签 java database jpa vaadin vaadin7

我正在尝试制作一个表单,将数据发送到 Vaadin 中的数据库。

Bean Person.java是一个典型的JavaBean:

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Person implements Serializable {

@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;

public Person(Long id, String firstName, String lastName) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
}

public Person() {
}

-- getters and setters --

Vaadin FieldGroup 如下所示:

FieldGroup fieldGroup = new BeanFieldGroup<Person>(Person.class);

// from the tutorial: "We need an item data source before we create the fields to be able to
// find the properties, otherwise we have to specify them by hand"
fieldGroup.setItemDataSource(new BeanItem<Person>(new Person(1L,
     "John", "Doe")));

for (Object propertyId : fieldGroup.getBoundPropertyIds()) {
    layout.addComponent(fieldGroup.buildAndBind(propertyId));
}

页面上没有任何内容。没有生成任何内容,也没有表单字段。我错过了什么吗?老实说,我对 Vaadin 完全陌生。另一方面,我想知道如何处理 ID 字段。它是自动生成的,因此用户不会对此值产生任何影响...我迷路了。

最佳答案

我的建议是这样的:

public class MyUI extends UI {

    @Override
    protected void init(VaadinRequest request) {
        VerticalLayout layout = new VerticalLayout();
        FieldGroup fieldGroup = new BeanFieldGroup<Person>(Person.class);
        fieldGroup.setItemDataSource(new BeanItem<Person>(new Person(1L, "John", "Doe")));
        for (Object propertyId : fieldGroup.getUnboundPropertyIds()) {
            Field<?> field = fieldGroup.buildAndBind(propertyId);
            if ("id".equals(propertyId)) {
                field.setReadOnly(true);
            }
            layout.addComponent(field);
        }
        setContent(layout);
    }

}

您应该使用 getUnboundPropertyIds(),因为您在迭代之前尚未将任何 propertyId 绑定(bind)到字段。

关于java - 如何在 Vaadin 中处理包含 @Id @GenerateVaule 的 bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26272009/

相关文章:

java - 为什么使用 useDelimiter(Pattern 模式) 与 useDelimiter(String 模式)

mysql - 获取两个表列的总和

database - 小于 1.0 的数字字段的 Delphi TFloatField.DisplayFormat

java - Spring 应用程序失败,Autowire 在 main.class 中为 null

java - JPA 双向关系

java - 如何在达到 maxLength 后更改最后一个数字

java - 如何通过 Selenium Webdriver 检索元素的 HTML?

java - 实现基于配置将数据存储在不同数据库中的单一功能的最佳方法是什么?

java - Hibernate将表id作为外键插入另一个表中

java - JSR 352 Spring 批处理 : Transaction Management