我在这个实体中有User实体和字段Role角色是ENUM。我正在尝试从UI创建用户。然而,我得到了一个例外:
org.springframework.beans.NullValueInNestedPathException: Invalid property 'role' of bean class [com.bionic.entities.User]: Could not instantiate property type [com.bionic.entities.Role] to auto-grow nested property path: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bionic.entities.Role]: Is it an abstract class?; nested exception is java.lang.InstantiationException: com.bionic.entities.Role
这是我的角色。枚举:
package com.bionic.entities;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Resource
public enum Role {
ADMINISTRATOR(1, "administrator"),
TRAINER(2, "trainer"),
STUDENT(3, "student"),
RESTRICTED_ADMINISTRATOR(4, "restricted_administrator"),
RESTRICTED_TRAINER(5, "restricted_trainer");
private long id;
private String name;
Role(){}
private Role(long id, String name) {
this.name = name;
this.id = id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
我的User.class字段:
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
@Column(name = "email", nullable = false, unique = true)
private String email;
@Column(name = "password", nullable = false)
private String password;
@Column(name = "cell")
private String cell;
@Column(name="position")
private String position;
@Enumerated(EnumType.ORDINAL)
@Column(name = "role_id")
private Role role;
最后,我的html表单:
<form method="POST" action="/superAdmin/addUser" th:object="${user}">
<select name="role.id" size="2" th:field="*{role.id}" style="display: block" id="role.id"></select>
<br /> <br /> <input type="submit" value="Upload" class="submit-but">
我花了两天时间来解决这个问题。然而,并不成功
在之后我如何创建实体
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public
@ResponseBody
String addUser(@ModelAttribute User user, Model model) {
try {
model.addAttribute("user", user);
superAdministratorService.addUser(user);
return "successful";
} catch (Exception e) {
return "You failed to upload";
}
}
Role
有一个默认的包级构造函数和一个带2个参数的私有构造函数,请尝试将包级构造函数更改为public
Role(){}
通过
public Role(){}
我认为这就是你问题的原因。但是您不能在enum中设置公共构造函数,所以您可能必须将实现更改为最终类。
更新
public static Role fromId(long id) {
if (1 == id) {
return ADMINISTRATOR;
}
// TODO else if for the rest of enum instances
} else {
throw new AssertionError("Role not know!");
}
}
一个可能的解决方案如下:
- 在
addUser
方法中使用DTO(与User
实体、getter和setter具有相同属性的简单POJO)来接收对象,因为DTO将role
定义为整数 - 在您的枚举中,创建一个类似上面的方法
- 从de-DTO对象创建实体对象,使用上面的方法在
User
实体中设置role
成员