栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

PostgreSQL枚举和Java枚举之间的休眠映射

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PostgreSQL枚举和Java枚举之间的休眠映射

高品质

正确别名并使用 合格的属性名称 是解决方案的第一部分。

    <query name="getAllMoves">        <![CDATA[ from Move as move where move.directionToMove = :direction        ]]>    </query>

休眠映射

@Enumerated(EnumType.STRING)
仍然无法正常工作,因此需要自定义
UserType
。关键是要正确覆盖
nullSafeSet
此答案中的网络实现。

@Overridepublic void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {    if (value == null) {        st.setNull(index, Types.VARCHAR);    }    else {        st.setObject(index, ((Enum) value).name(), Types.OTHER);    }}

车辆改道

implements ParameterizedType
没有合作:

org.hibernate.MappingException: type is not parameterized: full.path.to.PGEnumUserType

所以我不能这样注释enum属性:

@Type(type = "full.path.to.PGEnumUserType",        parameters = {     @Parameter(name = "enumClass", value = "full.path.to.Move$Direction")        })

相反,我这样声明了该类:

public class PGEnumUserType<E extends Enum<E>> implements UserType

使用构造函数:

public PGEnumUserType(Class<E> enumClass) {    this.enumClass = enumClass;}

不幸的是,这意味着任何其他类似映射的枚举属性都需要这样的类:

public class HibernateDirectionUserType extends PGEnumUserType<Direction> {    public HibernateDirectionUserType() {        super(Direction.class);    }}

注解

注释属性,您就完成了。

    @Column(name = "directiontomove", nullable = false)    @Type(type = "full.path.to.HibernateDirectionUserType")    private Direction directionToMove;

其他注意事项

  • EnhancedUserType
    以及它想要实现的三种方法
        public String objectToSQLString(Object value)    public String toXMLString(Object value)    public String objectToSQLString(Object value)

没什么区别,所以我坚持了

implements UserType

  • 根据您使用类的方式,可能不一定要通过重写
    nullSafeGet
    两个链接的解决方案的方式来使其特定于Postgres 。
  • 如果您愿意放弃postgres枚举,则可以创建该列
    text
    ,并且原始代码可以正常运行而无需额外的工作。


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/569262.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号