我可以将 Play 配置为使用 mysql 枚举而不是整数吗? [英] Can I configure Play to use mysql enums instead of ints?

查看:13
本文介绍了我可以将 Play 配置为使用 mysql 枚举而不是整数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型包含一个枚举,它由 JPA 映射到我的 mysql 数据库上的 int 列.

My model contains an enum, which are mapped by JPA to an int column on my mysql database.

mysql 有原生的 enum 类型,使用起来会更方便.

mysql has a native enum type, that would be more convenient to use.

如何配置 JPA 以使用这种类型?

How can I configure JPA to use this type?

@Entity
public class User extends Model {
  public enum Role {
    User,
    Moderator,
    Admin,
  }

  public Role role;
}

推荐答案

没有对 enum AFAIK 的内置支持,但也许您可以尝试将其作为解决方法(我从未测试过):

There is no built in support for enum AFAIK, but maybe you can try this as workaround (I never test it thought):

@Entity
public class User extends Model {
    public enum Role {
        User,
        Moderator,
        Admin,
    }

    @Enumerated(EnumType.STRING)
    @Column(columnDefinition = "ENUM('User', 'Moderator', 'Admin')")
    public Role role;
}

您可以使用 EnumType.STRING将值作为字符串存储在数据库中.
但是使用本机 ENUM 需要您使用 @Column 注释,需要将您的所有角色都在那里进行硬编码,您明白吗?此处重复.

You can use EnumType.STRING which will store the value as String in the database.
But using native ENUM require you to define the columnDefinition using @Column annotation which need all your roles to be harcoded there, you see? duplication here.

这篇关于我可以将 Play 配置为使用 mysql 枚举而不是整数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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