【问题标题】:How to Convert enum field to a String in a spring boot application saving to a mysql varchar columnm如何在 Spring Boot 应用程序中将枚举字段转换为字符串,保存到 mysql varchar 列
【发布时间】:2019-10-06 14:15:42
【问题描述】:

我有一个用户类型为管理员、客户和供应商的枚举类。我在用户模型类中使用 @Enumerated(EnumType.STRING) 注释了我的 userType 属性。但是,当我运行我的代码时,我遇到了类型不匹配的错误。

我在 Enum 用户类型字段中使用带有 varchar 的 spring boot 和 mysql 数据库。我下面的代码有更多的细节。

我的枚举类

UserType.java

   public enum UserType {

     CLIENT ("Client"),
     SUPPLIER ("Supplier"),
     ADMIN ("Admin");

     private final String type;

     UserType (String userType){

       this.type = userType;

     }

     public String getType() {

       return this.type;
     }
   }

User.java

UserType utype 的代码 sn-p。

@Entity
public class User{

 @Enumerated(EnumType.STRING)
 @Column (name = "user_type", nullable = false)
 private UserType utype;

 @Enumerated(EnumType.STRING)
 public UserType getUtype() {

   return utype;
 }

 @Enumerated(EnumType.STRING)
 public void setUtype(UserType utype) {
   this.utype = utype;
 }
}

控制器

   @GetMapping(value="/newUser")
   public String registrationForm(Model model){
     model.addAttribute("user", new User());
     model.addAttribute("UserTypes", UserType.values());

     return "register";
   }

  @PostMapping(value="/registerUser")
  public String registerUser(@ModelAttribute(value = "user") User user){

        userService.save(user);
        return "pages/login";
   }

百里香查看文件

register.html

     <select th:field="*{utype}" >
      <option th:each="usertype : ${UserTypes}"
             th:text="${usertype.type}"
     th:value="utype">
    </option>
    </select>

我希望将 utype 的输入转换为字符串,但出现以下错误。

字段“utype”上的对象“user”中的字段错误:拒绝值 [utype];代码 [typeMismatch.user.utype,typeMismatch.utype,typeMismatch.com.grocery.demo.Model.UserType,typeMismatch];参数 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码 [user.utype,utype];论据 [];默认消息 [utype]];默认消息 [无法将类型“java.lang.String”的属性值转换为属性“utype”所需的类型“com.grocery.demo.Model.UserType”;嵌套异常是 org.springframework.core.convert.ConversionFailedException: 无法从类型 [java.lang.String] 转换为类型 [@javax.persistence.Enumerated @javax.persistence.Column com.grocery.demo.Model.UserType]对于值“utype”;嵌套异常是 java.lang.IllegalArgumentException: No enum constant com.grocery.demo.Model.UserType.utype]]

mysql是使用application.properties配置的

spring.datasource.url=jdbc:mysql://localhost:3306/FredSystems
spring.datasource.username=root
spring.datasource.password=fred@2017
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create

spring.jpa.show-sql=true
spring.messages.basename=validation


 spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

【问题讨论】:

  • 你能分享你正在获取数据的数据库条目吗
  • 您是否检查了 utype 中返回的内容?很可能是一个对象
  • 我已经发布了错误日志,字段 'utype' 上的对象 'user' 中的字段错误:拒绝值 [utype];我不明白出了什么问题
  • 我已经发布了我的数据库连接@AmitD
  • @gybandi 我将不胜感激。为我的问题投票。

标签: java spring-boot spring-mvc


【解决方案1】:

做起来很简单:

控制器

 @GetMapping(value="/newUser")
   public String registrationForm(Model model){
     model.addAttribute("user", new User());
     model.addAttribute("UserTypes",Arrays.asList(UserType.values()));
     return "register";
   }

在你的百里香叶中:

<select th:field="*{utype}" >
      <option th:each="usertype : ${UserTypes}"
             th:text="${usertype}"
     th:value="${usertype}">
    </option>
    </select>

如果是 JSP:

<select id="editState"class="form-control">
                        <c:forEach items="${UserTypes}" var="ut" varStatus="loop">
                            <option value="${ut}">${ut}</option>
                        </c:forEach>                        
                    </select>

【讨论】:

  • 你能清理项目并重新构建吗??
  • 请查看我上面的更新代码,包括控制器的 PostMapping
【解决方案2】:

在你的枚举中添加这个方法

public static UserType getByName(String name) {
        for (UserType type : UserType.values()) {
            if (type.getName().equals(name)) {
                return type;
            }
        }
        return null;
    }

在你的百里香中

<select th:field="*{utype}" >
      <option th:each="usertype : ${UserTypes}"
             th:text="${usertype.type}"
     th:value="${utype.type}">
    </option>
    </select>

然后从后端尝试使用 getByName 方法来解析您的 HTML 输入。

【讨论】:

  • 嘿伙计,检查我是否添加了我用来向数据库提交数据的 PostMapping
【解决方案3】:

首先,尝试在 enum 中有一个与您的 ENUM 值完全匹配的字段。这将便于获取任何枚举

例如

public enum UserType {

 CLIENT ("CLIENT","Client"),
 SUPPLIER ("SUPPLIER","Supplier"),
 ADMIN ("ADMIN","Admin");

 private final String type;
 private final String name;

 UserType (String name, String userType){
   this.name=name;
   this.type = userType;

 }

 public String getType() {

   return this.type;
 }

}

出于您的目的,您可以尝试根据您的值覆盖 toString() 方法。

【讨论】:

  • 那么你同意我的 PostMapping 控制器吗?据你所知可以吗
【解决方案4】:

问题出在您的 register.html 中:

   <select th:field="*{utype}" >
      <option th:each="usertype : ${UserTypes}"
             th:text="${usertype.type}"
     th:value="utype">
    </option>
    </select>

在 th:value 标记中,您对 utype 字段的引用不正确。您应该使用变量表达式,在其中声明要绑定到 User 对象的 utype fieldvalue。所以应该是这样的:

   <select th:field="*{utype}" >
      <option th:each="usertype : ${UserTypes}"
             th:text="${usertype.type}"
     th:value="${usertype}">
    </option>
    </select>

如果仍然无法正常工作,请查看我更新的示例项目: https://github.com/gybandi/spring-ui-demo

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 2010-10-03
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2022-01-10
    • 2013-06-27
    • 2022-06-10
    相关资源
    最近更新 更多