【问题标题】:How to map some table columns to a Map with the column names as key如何将某些表列映射到以列名作为键的 Map
【发布时间】:2021-01-06 18:08:37
【问题描述】:

我有这张桌子:

CREATE TABLE user_type (
    id TINYINT NOT NULL AUTO_INCREMENT,
    name VARCHAR(20) UNIQUE NOT NULL,
    ...
    --Some more columns

    can_create BOOLEAN NOT NULL,
    can_edit BOOLEAN NOT NULL,
    can_delete BOOLEAN NOT NULL,
    ...
    --Has 23 more columns that define different permissions

    PRIMARY KEY (id)
);

并且想把它映射成这样的:

@Entity
@Table(name = "user_type")
public class UserType{
    @Id
    private Byte id;

    private String name;

    // Some more fields

    //Then this map should contain the remaining 26 permission columns
    //with the column names (can_create, can_edit, etc.) as keys.
    @???
    private Map<String, Boolean> permissions;
}

是否可以像这样将某些列映射到Map?在我发现的所有示例和问题中,它们只是将两个值映射在一起,而不是列名与其值。

【问题讨论】:

  • 最好对单个列中的值进行位掩码。并编写一个 AttributeConverter 来存储和获取地图。
  • 如果关系是一对一的,那你为什么需要这样的permissions映射呢?
  • @Rono 您的意思是将所有权限值作为位存储在单个列中吗?这不会使在此实现之外的维护和查询变得更加困难吗?
  • @Raj 如果我正确理解您的问题,它可能是单个类“UserType”,其中“permissions”字段是 Map,不需要“UserTypePermissions”类。但问题还是一样,如何将那些列名和值映射到所述 Map?
  • @Ludenife 不,我的意思是说,如果保证一个UserType 恰好有一个UserTypePermissions,那么您根本不需要地图。而且这个设计看起来很奇怪,user_type 有一个 fk 映射到 user_type_permissions 的 pk。恕我直言,应该反过来

标签: java hibernate jpa


【解决方案1】:

您可以尝试使用以下方法。

  1. 创建一个代表您的权限类型的枚举:
public enum PermissionType
{
   CREATE,
   EDIT,
   DELETE

   // other permissions ...
}
  1. 创建Permissions 类来保存用户的权限状态。
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Permissions implements Serializable
{
   private Map<PermissionType, Boolean> permissions;
   
   public Permissions()
   {
      permissions = new HashMap<>(PermissionType.values().length);
      for (PermissionType permType : PermissionType.values())
      {
         permissions.put(permType, false);
      }
   }
   
   public void setPermission(PermissionType name, Boolean value)
   {
      permissions.put(name, value);
   }
   
   public Map<PermissionType, Boolean> getPermissions()
   {
      return permissions;
   }
   
   @Override
   public int hashCode()
   {
      return permissions.hashCode();
   }

   @Override
   public boolean equals(Object obj)
   {
      if (this == obj) return true;
      if (obj == null) return false;
      if (getClass() != obj.getClass()) return false;

      Permissions other = (Permissions) obj;
      return Objects.equals(other.permissions, permissions);
   }
}
  1. 按以下方式为Permissions 创建休眠custom basic type
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Map;
import java.util.Objects;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;

public class PermissionUserType implements UserType
{
   private static final int[] SQL_TYPES;
   
   static {
      SQL_TYPES = new int[PermissionType.values().length];
      for (int ind = 0; ind < SQL_TYPES.length; ind++)
      {
         SQL_TYPES[ind] = Types.BOOLEAN;
      }
   }
   
   @Override
   public int[] sqlTypes()
   {
      return SQL_TYPES;
   }

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

   @Override
   public boolean equals(Object x, Object y) throws HibernateException
   {
       return Objects.equals(x, y);
   }

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

   @Override
   public Permissions nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException
   {
      /*
       * The names are column aliases generated by hibernate, like can_dele5_5_, can_crea3_5_, ...
       **/
      Permissions permissions = new Permissions();
      for (int ind = 0; ind < names.length; ind++)
      {
         Boolean val = rs.getBoolean(names[ind]);
         PermissionType name = PermissionType.values()[ind];
         permissions.setPermission(name, val);
      }
      return permissions;
   }

   @Override
   public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException
   {
       if (Objects.isNull(value))
       {
          for (int ind = 0; ind < SQL_TYPES.length; ind++)
          {
             st.setNull(index + ind, SQL_TYPES[ind]);
          }
       }
       else
       {
          Permissions permissions = (Permissions) value;
          for (Map.Entry<PermissionType, Boolean> permEntry : permissions.getPermissions().entrySet())
          {
             Integer ind = permEntry.getKey().ordinal();
             st.setObject(index + ind, permEntry.getValue(), SQL_TYPES[ind]);
          }
       }
   }

   @Override
   public Permissions deepCopy(Object value) throws HibernateException
   {
      if (value == null) return null;
       
      Permissions oldPerms = (Permissions) value;
      Permissions newPerms = new Permissions();
      for (Map.Entry<PermissionType, Boolean> permEntry : oldPerms.getPermissions().entrySet())
      {
         newPerms.setPermission(permEntry.getKey(), permEntry.getValue());
      }
      return newPerms;
   }

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

   @Override
   public Serializable disassemble(Object value) throws HibernateException
   {
       return deepCopy(value);
   }

   @Override
   public Object assemble(Serializable cached, Object owner) throws HibernateException
   {
       return deepCopy(cached);
   }

   @Override
   public Object replace(Object original, Object target, Object owner) throws HibernateException
   {
       return deepCopy(original);
   }
}
  1. 然后在您的实体映射中使用此自定义基本类型:
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Type;

@Entity
@Table(name = "user_type")
public class UserTypeEntity
{
   @Id
   @Column(name = "id")
   private Long id;

   @Column(name = "name")
   private String name;

   @Type(type = "com.me.PermissionUserType")
   @Columns(columns = {
      // the order should be matched with the enum PermissionType
      @Column(name = "can_create"),
      @Column(name = "can_edit"),
      @Column(name = "can_delete")
   })
   private Permissions permissions;
   
   // ...
}

【讨论】:

  • 谢谢。我想这就是我一直在寻找的。让我试试看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
  • 1970-01-01
  • 2015-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多