我在此实体中拥有用户实体和字段角色。 角色为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
这是我的 Role.Enum :
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">
为了解决这个问题,我花了2天时间。然而,它并不成功
我如何创建实体:
@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";
}
}
答案 0 :(得分:1)
Role
有一个默认的包级构造函数和一个带有2个参数的私有构造函数,尝试将包级别的构造函数更改为public,以便执行此操作,更改
Role(){}
通过
public Role(){}
我认为这是导致问题的原因。但是你不能在枚举中设置公共构造函数,所以也许你必须将你的实现改为最终的类。
<强>更新强>
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!");
}
}
可能的解决方案如下:
User
实体和getter和setter相同属性的简单POJO)在addUser
方法中接收对象,在该DTO中将role
定义为整数。 role
实体中设置User
成员。