没有将枚举值保存在数据库中,我想就是这样,或者我不明白,我试图保存,因为控制台向我显示了数据,但是当我从数据库询问时,我得到了另一个值

@Entity
@Table(name = "User")
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "name")
    private String name;

    @Column(name = "password")
    private String password;

    @Column(unique = true, name = "email")
    private String email;

    @Column(name="rol")
    Rol rol;



    @Column(name = "life")
    Life life;


    public User() {

    }
    }


我在.info中有此邮件,显示此消息“ OWNER”

Set<User> users =new HashSet<>();
            log.info("CONSOLE"+ user.getRol());
            users.add(user);
            meet.setUsers(users);
            return meetRepository.save(meet);


但是大张旗鼓我得到了其他价值
角色:参与者

[
  {
    "id": 1,
    "name": "string2",
    "state": "pause",
    "bet": {
      "profit": 0,
      "inversion": 0
    },
    "users": [
      {
        "id": 1,
        "name": "string",
        "password": "string",
        "email": "ema",
        "rol": "PARTICIPANT",
        "life": "suspend"
      }
    ]
  }
]

最佳答案

如果您的字段rol和life是Enums,则必须使用@Enumerated将其声明为Enums。有两种选择。默认将存储序数。或者,您可以选择使用字符串名称存储在数据库中。就可维护性而言,这是更好的选择:

@Enumerated(EnumType.STRING)
@Column(name="rol")
Rol rol;

@Enumerated(EnumType.STRING)
@Column(name = "life")
Life life;


两句话:


当数据库字段具有与属性相同的名称时,可以省略@Column。而且,如果表与实体具有相同的名称,则@Table注解也是如此。
在我的一篇文章中了解有关Enums和JPA的更多信息,如果您真的应该使用它:https://72.services/de/should-you-use-enums-with-jpa/

10-04 10:19
查看更多