java - 将一些 boolean 属性映射为 Hibernate 中的枚举集

标签 java hibernate

我有一个实体,它在数据库中有一些 BIT 字段:

  • 可编辑
  • 需要审核
  • 活跃

这些字段映射到 boolean其 Java 类中的字段使用 Hibernate 3.6.9 版本。这迫使我为我想要获取的每个实体列表编写一个接口(interface)方法:

List<Entity> listEditables();
List<Entity> listReviewNeeded();
List<Entity> listActives();

或者写一个通用的接口(interface)方法来实现它们的组合:

List<Entity> listEntities(boolean editables, boolean reviewNeeded, boolean actives);

第二个选择看起来更好,但是如果我将来添加另一个字段,将需要修改接口(interface)本身(以及与之耦合的每一行代码)。

所以我决定我可以将它表示为枚举 Set :

public enum EntityType{
    EDITABLE, REVIEW_NEEDED, ACTIVE
}

//That way there's no need to change interface method's signature
List<Entity> listEntities(Set<EntityType> requiredTypes);

作为枚举符合我想要实现的目标是有道理的,Entity类型本身应该有自己的 Set<EntityType> :

public class Entity{
    Set<EntityType> entityTypes;
}

然而,我有逻辑上匹配 Set 的映射 boolean 值,而不是那个.那么我的问题是,有没有办法映射Set<EntityType> entityTypes在基于 BIT 字段的 hibernate 中,还是我必须自己管理该逻辑,将它们设置为 boolean

更新

将它们映射为 Set意味着可以使用 in 查询列表子句,如果不是,则意味着在我的 Controller 和模型代码之间进行转换需要额外的步骤。

Set<EntityType> typesSet = Sets.newHashSet(EntityType.EDITABLE, EntityType.REVIEW_NEEDED);
//Obtains a list of every single entity which is EDITABLE or REVIEW_NEEDED
session.createCriteria(Entity.class).addRestriction(Restrictions.in("entityTypes",typeSet)).list();

最佳答案

我想我有一个解决方案。您感兴趣的是 CompositeUserType。

作为示例,让我们使用我最近编写的 InetAddress 复合用户类型将 128 位 IPv6 地址/IPv4Address 对象映射到用户帐户实体内的两个 64 位长属性。

signupIp:InetAddress 被映射到两列(没有列数限制或类似的):

    @Columns(columns = {@Column(name = "ip_low", nullable = true), @Column(name = "ip_high", nullable = true)})
    private InetAddress signupIp;

实现的有趣部分如下所示:

public class InetAddressUserType implements CompositeUserType {
@Override
public String[] getPropertyNames() {
    return new String [] {"ipLow", "ipHigh"};
}

@Override
public Type[] getPropertyTypes() {
    return new Type [] { LongType.INSTANCE, LongType.INSTANCE};
}

@Override
public Object getPropertyValue(Object component, int property) throws HibernateException {
    if(component != null)
        return toLong((InetAddress)component)[property];
    else
        return null;
}

@Override
public void nullSafeSet(PreparedStatement st, Object value, int index,
        SessionImplementor session) throws HibernateException, SQLException {

    if(value != null) {
        long [] longs = toLong((InetAddress)value);
        st.setLong(index, longs[0]);
        st.setLong(index + 1, longs[1]);
    }
    else {
        st.setNull(index, LongType.INSTANCE.sqlType());
        st.setNull(index + 1, LongType.INSTANCE.sqlType());
    }
}

@Override
public void setPropertyValue(Object component, int property, Object value)
        throws HibernateException {
    throw new RuntimeException("This object is immutable");
}

@Override
public Class<?> returnedClass() {
    return InetAddress.class;
}

@Override
public boolean equals(Object x, Object y) throws HibernateException {
    return x != null ? x.equals(y) : null == y;
}

@Override
public int hashCode(Object x) throws HibernateException {
    return x.hashCode();
}

@Override
public Object nullSafeGet(ResultSet rs, String[] names,
        SessionImplementor session, Object owner)
        throws HibernateException, SQLException {
    Long ipLow = rs.getLong(names[0]);
    if(!rs.wasNull()) {
        Long ipHigh = rs.getLong(names[1]);

        try {
            return fromLong(new long [] {ipLow, ipHigh});
        } catch (UnknownHostException e) {
            throw new HibernateException("Failed to get InetAddress: ip = " + ipHigh + " + " + ipLow, e);
        }
    }
    else
        return null;
}

@Override
public Object deepCopy(Object value) throws HibernateException {
    if(value != null)
        try {
            return InetAddress.getByAddress(((InetAddress)value).getAddress());
        } catch (UnknownHostException e) {
            throw new RuntimeException("Impossible Exception: " + e.getMessage(), e);
        }
    else
        return null;
}

@Override
public boolean isMutable() {
    return false;
}
    ...
 }

请注意,我根据 ipLow 和 ipHigh 的值在 Inet4Address 和 Inet6Address 实例之间灵活切换。复合标记为不可变,您需要查看 Hibernate 源代码中的文档和示例(内置复合用户类型)。

以类似的方式,您可以映射有意义的位属性。您可以使用一个引用您的 EnumType 的 Restriction.eq 来查询这些位。您可以使用 equals 方法来检查属性对象。如果您需要引用一个特殊的映射位,您可以像 signupIp.ipLow 一样使用点符号来引用 ipLow 属性/列。

我想这就是您要找的。

更新:

最后归结为定义属性的正确顺序。 Hibernate 将始终使用整数索引值来访问每个属性:

//immutable for simplicity
class Status {
     private final boolean editable;
     private final boolean needsReview;
     private final boolean active;
     //... constructor + isEditable etc..
}

在您的 StatusCompositeType 类中:

public String[] getPropertyNames() {
  return new String [] {"editable", "needsReview", "active"};
}

public Type[] getPropertyTypes() {
  return new Type [] { BooleanType.INSTANCE, LongType.INSTANCE};
}

public Object getPropertyValue(Object component, int property) throws HibernateException {
if(component != null) {
   Status status = (Status)component;
   switch(property) {
   case 1: return status.isEditable();
   case 2: return status.isReviewNeeded();
   case 3: return status.isActive();
   default: throw new IllegalArgumentException();
   }
}
else
    return null; //all columns can be set to null if you allow a entity to have a null status.
}


public void nullSafeSet(PreparedStatement st, Object value, int index,
    SessionImplementor session) throws HibernateException, SQLException {

  if(value != null) {
    Status status = (Status)value;
    st.setBoolean(index, status.isEditable());
    st.setBoolean(index + 1, status.isReviewNeeded());
    st.setBoolean(index + 2, status.isActive());
  }
  else {
    st.setNull(index, BooleanType.INSTANCE.sqlType());
    st.setNull(index + 1, BooleanType.INSTANCE.sqlType());
    st.setNull(index + 2, BooleanType.INSTANCE.sqlType());
  }
}

public Object nullSafeGet(ResultSet rs, String[] names,
    SessionImplementor session, Object owner)
    throws HibernateException, SQLException {
  Boolean isEditable = rs.getBoolean(names[0]);
  if(!rs.wasNull()) {
    Boolean isReviewNeeded = rs.getBoolean(names[1]);
    Boolean isActive = rs.getBoolean(names[2]);

    return new Status(isEditable, isReviewNeeded, isActive);
  }
  else
    return null;
}

剩下的很简单。在创建 sessionFactory 之前,请记住为用户类型实现 equals 和 hashcode,并将类型添加到配置中。

一旦一切就绪,您就可以创建条件搜索并使用:

//search for any elements that have a status of editable, no reviewNeeded and is not active (true false false).
criteria.add(Restrictions.eq("status", new Status(true, false, false));

现在您的 listEntities 方法可能变成:listEntities(Status status)listEntities(boolean editable, boolean reviewNeeded, boolean isActive) .

如果您需要其他信息,只需查看 Hibernate 在其自己的源代码中提供的 CompositeType 和 BasicType 实现(查找 CompositeType 和 BasicType 的实现者)。了解这些有助于使用和学习 Hibernate 的中级知识。

关于java - 将一些 boolean 属性映射为 Hibernate 中的枚举集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18612527/

相关文章:

java - 使用两个 FileWriter,其中一个追加,另一个不追加

java - Kotlin objects & companion objects & lazy 如何处理内存

java - 从另一个 Activity 访问对象

hibernate - Grails似乎具有错误的 hibernate 依赖关系

java - ehcache缓存项错误

java - 将 java web 服务 json 消费到 Angular 4 中

java - 使用 Java 获取 google searchResultTime

java - 有什么简单的方法可以持久化一个包含许多对其他实体对象的引用的对象?

java - 级联坚持父级后, child 的 ID 不存在

java - 提交实体对象后检索子对象