Not save an enum value in the database, why?

流过昼夜 提交于 2021-01-29 09:08:42

问题


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() {

    }
    }

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);

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"
      }
    ]
  }
]

回答1:


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;

Two remarks:

  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.

  2. 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/




回答2:


When you save a Enum to the database as stated above you have the option of saving it as String or as Numerical Ordinal. The numerical option is very painfull because every time you need to update your enum values or change the order of the values you will mess with your database options for the field. Also another thing that is very painfull even when you store the strings on the database is that when you are using some ORM such as Hibernate and you have NULL values. So keep your enums as strings and avoid NULL value.



来源:https://stackoverflow.com/questions/56179567/not-save-an-enum-value-in-the-database-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!