高品质
正确别名并使用 合格的属性名称 是解决方案的第一部分。
<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
,并且原始代码可以正常运行而无需额外的工作。



