gpt4 book ai didi

java - 在 EBean 和表单中保存枚举列表

转载 作者:行者123 更新时间:2023-11-30 03:36:13 25 4
gpt4 key购买 nike

我有一个“角色”字段,其中包含枚举项。我正在尝试使用表单编辑此列表,但得到:

[InvalidPropertyException: Invalid property 'roles[0]' of bean class [models.Device]: Property referenced in indexed property path 'roles[0]' is neither an array nor a List nor a Map; returned value was [SERVER]]

这是我的实体:

@Entity
public class Device extends Model {

@Id
@Constraints.Min(1)
public Long id;

@Constraints.Required
public String name;

@Constraints.Required
public String ipAddress;

@Constraints.Required
@ElementCollection(fetch = FetchType.EAGER)
public Set<DeviceRole> roles = new HashSet<DeviceRole>(Arrays.asList(DeviceRole.OTHER));

@Version
public Timestamp lastUpdate;

public static Finder<Long,Device> find = new Finder<Long,Device>(
Long.class, Device.class
);

public List<ValidationError> validate() {
/*
List<ValidationError> errors = new ArrayList<ValidationError>();
if (User.byEmail(email) != null) {
errors.add(new ValidationError("email", "This e-mail is already registered."));
}
return errors.isEmpty() ? null : errors;
*/
return null;
}
}

Controller 中的编辑和更新功能:

public static Result edit(Long id) {
Device device = Device.find.byId(id);
Form<Device> myForm = Form.form(Device.class);
myForm = myForm.fill(device);

return ok(views.html.Devices.edit.render(myForm, listOfRoles()));
}

public static Result update() {
Form<Device> deviceForm = Form.form(Device.class).bindFromRequest();

if (deviceForm.hasErrors()) {
return badRequest(views.html.Devices.edit.render(deviceForm, listOfRoles()));
}

// Form is OK, has no errors, we can proceed
Device device = deviceForm.get();
device.update(device.id);
return redirect(routes.Devices.index());
}

private static List<String> listOfRoles() {
List<String> list = new ArrayList<String>();
for(DeviceRole role : DeviceRole.values()) {
list.add(role.toString());
}
return list;
}

模板:

@main("Edit a device") {

@helper.form(action = routes.Devices.update()) {
@helper.inputText(myForm("name"))
@helper.inputText(myForm("ipAddress"))

@helper.select(myForm("roles"), options(deviceRoles), 'multiple->"multiple")

<input type="hidden" name="id" value="@myForm("id").value">
<input type="submit" value="Submit">
}

<a href="@routes.Devices.index()">Cancel</a>
}

最佳答案

实际上,可能要这样做,您需要将它们保存为字符串字段中逗号分隔的值列表,为了使其更清晰,我建议将 DeviceRole 更改为 Ebean 模型,将其作为常见的多对多关系处理。

恕我直言,它为您提供了更大的灵 active ,并且还允许在未来创建更多动态角色,

刚刚 fork 了您的示例并对其进行了修改,以展示我自己如何做(自述文件中的一些详细信息):

https://github.com/biesior/temperature-control

P.S.:看看 Ebean 的票证,如果到目前为止没有任何变化,只是还不支持保存枚举列表(我不知道当前状态)http://avaje.org/topic-149.html

关于java - 在 EBean 和表单中保存枚举列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27840090/

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