gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:26:47 27 4
gpt4 key购买 nike

我正在尝试制作一个表单,将数据发送到 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com