没有在数据库中保存一个枚举值,为什么? [英] Not save an enum value in the database, why?

查看:124
本文介绍了没有在数据库中保存一个枚举值,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does not save an enum value in the database, I think that's it, or I do not understand, I try to save since the console shows me a data, but when I ask from the database I get another value

@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"

i have this in the .info, show this message "OWNER"

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

但是大摇大摆我得到了其他价值 ROL:参与者

but in swagger i get other value ROL: PARTICIPANT

[
  {
    "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.有两种选择.默认将存储序数.或者,您可以选择使用字符串名称存储在数据库中.就可维护性而言,这是更好的选择:

If your fields rol and life are Enums you have to declare them as Enums with @Enumerated. There are two options. Default will store the ordinal number. Or you can choose to use the string name to store in the DB. That's the better option in terms of maintainability:

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

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

两句话:

  1. 当数据库字段具有与属性相同的名称时,可以省略@Column.并且,如果表与实体具有相同的名称,则@Table注解也是如此.

  1. When the database field has the same name as the attribute you can omit @Column. And if the table has the same name as the entity this is also true for the @Table annotatoin.

在我的一篇文章中阅读有关Enums和JPA的更多信息,如果您真的应该使用它: https://72.services/de/should-you-use-enums-with-jpa/

Read more about Enums and JPA and if you really should use it in one of my articles: https://72.services/de/should-you-use-enums-with-jpa/

这篇关于没有在数据库中保存一个枚举值,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆