如何将某些表列映射到一个以列名为键的 Map。

huangapple go评论94阅读模式
英文:

How to map some table columns to a Map with the column names as key

问题

我有这个表:

  1. CREATE TABLE user_type (
  2. id TINYINT NOT NULL AUTO_INCREMENT,
  3. name VARCHAR(20) UNIQUE NOT NULL,
  4. ...
  5. --还有更多列
  6. can_create BOOLEAN NOT NULL,
  7. can_edit BOOLEAN NOT NULL,
  8. can_delete BOOLEAN NOT NULL,
  9. ...
  10. --还有23个定义不同权限的列
  11. PRIMARY KEY (id)
  12. );

并且希望将其映射为类似于以下的内容:

  1. @Entity
  2. @Table(name = "user_type")
  3. public class UserType {
  4. @Id
  5. private Byte id;
  6. private String name;
  7. // 更多字段
  8. //然后这个映射应该包含剩余的26个权限列
  9. //列名(can_create、can_edit等)作为键。
  10. @???
  11. private Map<String, Boolean> permissions;
  12. }

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

英文:

I have this table:

  1. CREATE TABLE user_type (
  2. id TINYINT NOT NULL AUTO_INCREMENT,
  3. name VARCHAR(20) UNIQUE NOT NULL,
  4. ...
  5. --Some more columns
  6. can_create BOOLEAN NOT NULL,
  7. can_edit BOOLEAN NOT NULL,
  8. can_delete BOOLEAN NOT NULL,
  9. ...
  10. --Has 23 more columns that define different permissions
  11. PRIMARY KEY (id)
  12. );

And would like to map it to something like this:

  1. @Entity
  2. @Table(name = &quot;user_type&quot;)
  3. public class UserType{
  4. @Id
  5. private Byte id;
  6. private String name;
  7. // Some more fields
  8. //Then this map should contain the remaining 26 permission columns
  9. //with the column names (can_create, can_edit, etc.) as keys.
  10. @???
  11. private Map&lt;String, Boolean&gt; permissions;
  12. }

Is it possible to map some columns to a Map like that? In all the examples and questions I found they just map two values together, not a column name with its value.

答案1

得分: 1

你可以尝试使用以下方法:

  1. 创建一个枚举来表示权限类型:
  1. public enum PermissionType
  2. {
  3. CREATE,
  4. EDIT,
  5. DELETE
  6. // 其他权限...
  7. }
  1. 创建一个 Permissions 类来保存用户的权限状态:
  1. import java.io.Serializable;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import java.util.Objects;
  5. public class Permissions implements Serializable
  6. {
  7. private Map<PermissionType, Boolean> permissions;
  8. public Permissions()
  9. {
  10. permissions = new HashMap<>(PermissionType.values().length);
  11. for (PermissionType permType : PermissionType.values())
  12. {
  13. permissions.put(permType, false);
  14. }
  15. }
  16. public void setPermission(PermissionType name, Boolean value)
  17. {
  18. permissions.put(name, value);
  19. }
  20. public Map<PermissionType, Boolean> getPermissions()
  21. {
  22. return permissions;
  23. }
  24. @Override
  25. public int hashCode()
  26. {
  27. return permissions.hashCode();
  28. }
  29. @Override
  30. public boolean equals(Object obj)
  31. {
  32. if (this == obj) return true;
  33. if (obj == null) return false;
  34. if (getClass() != obj.getClass()) return false;
  35. Permissions other = (Permissions) obj;
  36. return Objects.equals(other.permissions, permissions);
  37. }
  38. }
  1. 以以下方式创建 hibernate 自定义基本类型 来表示 Permissions
  1. import java.io.Serializable;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Types;
  6. import java.util.Map;
  7. import java.util.Objects;
  8. import org.hibernate.HibernateException;
  9. import org.hibernate.engine.spi.SharedSessionContractImplementor;
  10. import org.hibernate.usertype.UserType;
  11. public class PermissionUserType implements UserType
  12. {
  13. private static final int[] SQL_TYPES;
  14. static {
  15. SQL_TYPES = new int[PermissionType.values().length];
  16. for (int ind = 0; ind < SQL_TYPES.length; ind++)
  17. {
  18. SQL_TYPES[ind] = Types.BOOLEAN;
  19. }
  20. }
  21. @Override
  22. public int[] sqlTypes()
  23. {
  24. return SQL_TYPES;
  25. }
  26. @Override
  27. public Class<?> returnedClass()
  28. {
  29. return Permissions.class;
  30. }
  31. @Override
  32. public boolean equals(Object x, Object y) throws HibernateException
  33. {
  34. return Objects.equals(x, y);
  35. }
  36. @Override
  37. public int hashCode(Object x) throws HibernateException
  38. {
  39. return Objects.hashCode(x);
  40. }
  41. @Override
  42. public Permissions nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException
  43. {
  44. /*
  45. * 列名是由 Hibernate 生成的列别名,如 can_dele5_5_, can_crea3_5_, ...
  46. **/
  47. Permissions permissions = new Permissions();
  48. for (int ind = 0; ind < names.length; ind++)
  49. {
  50. Boolean val = rs.getBoolean(names[ind]);
  51. PermissionType name = PermissionType.values()[ind];
  52. permissions.setPermission(name, val);
  53. }
  54. return permissions;
  55. }
  56. @Override
  57. public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException
  58. {
  59. if (Objects.isNull(value))
  60. {
  61. for (int ind = 0; ind < SQL_TYPES.length; ind++)
  62. {
  63. st.setNull(index + ind, SQL_TYPES[ind]);
  64. }
  65. }
  66. else
  67. {
  68. Permissions permissions = (Permissions) value;
  69. for (Map.Entry<PermissionType, Boolean> permEntry : permissions.getPermissions().entrySet())
  70. {
  71. Integer ind = permEntry.getKey().ordinal();
  72. st.setObject(index + ind, permEntry.getValue(), SQL_TYPES[ind]);
  73. }
  74. }
  75. }
  76. @Override
  77. public Permissions deepCopy(Object value) throws HibernateException
  78. {
  79. if (value == null) return null;
  80. Permissions oldPerms = (Permissions) value;
  81. Permissions newPerms = new Permissions();
  82. for (Map.Entry<PermissionType, Boolean> permEntry : oldPerms.getPermissions().entrySet())
  83. {
  84. newPerms.setPermission(permEntry.getKey(), permEntry.getValue());
  85. }
  86. return newPerms;
  87. }
  88. @Override
  89. public boolean isMutable()
  90. {
  91. return false;
  92. }
  93. @Override
  94. public Serializable disassemble(Object value) throws HibernateException
  95. {
  96. return deepCopy(value);
  97. }
  98. @Override
  99. public Object assemble(Serializable cached, Object owner) throws HibernateException
  100. {
  101. return deepCopy(cached);
  102. }
  103. @Override
  104. public Object replace(Object original, Object target, Object owner) throws HibernateException
  105. {
  106. return deepCopy(original);
  107. }
  108. }
  1. 然后在实体映射中使用这个自定义基本类型:
  1. import org.hibernate.annotations.Columns;
  2. import org.hibernate.annotations.Type;
  3. @Entity
  4. @Table(name = "user_type")
  5. public class UserTypeEntity
  6. {
  7. @Id
  8. @Column(name = "id")
  9. private Long id;
  10. @Column(name = "name")
  11. private String name;
  12. @Type(type = "com.me.PermissionUserType")
  13. @Columns(columns = {
  14. // 顺序应与 PermissionType 枚举顺序一致
  15. @Column(name = "can_create"),
  16. @Column(name = "can_edit"),
  17. @Column(name = "can_delete")
  18. })
  19. private Permissions permissions;
  20. // ...
  21. }
英文:

You can try to use the following approach.

  1. Create an enum that will represent your permission types:
  1. public enum PermissionType
  2. {
  3. CREATE,
  4. EDIT,
  5. DELETE
  6. // other permissions ...
  7. }
  1. Create Permissions class that will hold the permissions state for a user.
  1. import java.io.Serializable;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import java.util.Objects;
  5. public class Permissions implements Serializable
  6. {
  7. private Map&lt;PermissionType, Boolean&gt; permissions;
  8. public Permissions()
  9. {
  10. permissions = new HashMap&lt;&gt;(PermissionType.values().length);
  11. for (PermissionType permType : PermissionType.values())
  12. {
  13. permissions.put(permType, false);
  14. }
  15. }
  16. public void setPermission(PermissionType name, Boolean value)
  17. {
  18. permissions.put(name, value);
  19. }
  20. public Map&lt;PermissionType, Boolean&gt; getPermissions()
  21. {
  22. return permissions;
  23. }
  24. @Override
  25. public int hashCode()
  26. {
  27. return permissions.hashCode();
  28. }
  29. @Override
  30. public boolean equals(Object obj)
  31. {
  32. if (this == obj) return true;
  33. if (obj == null) return false;
  34. if (getClass() != obj.getClass()) return false;
  35. Permissions other = (Permissions) obj;
  36. return Objects.equals(other.permissions, permissions);
  37. }
  38. }
  1. Create hibernate custom basic type for the Permissions in the following way:
  1. import java.io.Serializable;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Types;
  6. import java.util.Map;
  7. import java.util.Objects;
  8. import org.hibernate.HibernateException;
  9. import org.hibernate.engine.spi.SharedSessionContractImplementor;
  10. import org.hibernate.usertype.UserType;
  11. public class PermissionUserType implements UserType
  12. {
  13. private static final int[] SQL_TYPES;
  14. static {
  15. SQL_TYPES = new int[PermissionType.values().length];
  16. for (int ind = 0; ind &lt; SQL_TYPES.length; ind++)
  17. {
  18. SQL_TYPES[ind] = Types.BOOLEAN;
  19. }
  20. }
  21. @Override
  22. public int[] sqlTypes()
  23. {
  24. return SQL_TYPES;
  25. }
  26. @Override
  27. public Class&lt;?&gt; returnedClass()
  28. {
  29. return Permissions.class;
  30. }
  31. @Override
  32. public boolean equals(Object x, Object y) throws HibernateException
  33. {
  34. return Objects.equals(x, y);
  35. }
  36. @Override
  37. public int hashCode(Object x) throws HibernateException
  38. {
  39. return Objects.hashCode(x);
  40. }
  41. @Override
  42. public Permissions nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException
  43. {
  44. /*
  45. * The names are column aliases generated by hibernate, like can_dele5_5_, can_crea3_5_, ...
  46. **/
  47. Permissions permissions = new Permissions();
  48. for (int ind = 0; ind &lt; names.length; ind++)
  49. {
  50. Boolean val = rs.getBoolean(names[ind]);
  51. PermissionType name = PermissionType.values()[ind];
  52. permissions.setPermission(name, val);
  53. }
  54. return permissions;
  55. }
  56. @Override
  57. public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException
  58. {
  59. if (Objects.isNull(value))
  60. {
  61. for (int ind = 0; ind &lt; SQL_TYPES.length; ind++)
  62. {
  63. st.setNull(index + ind, SQL_TYPES[ind]);
  64. }
  65. }
  66. else
  67. {
  68. Permissions permissions = (Permissions) value;
  69. for (Map.Entry&lt;PermissionType, Boolean&gt; permEntry : permissions.getPermissions().entrySet())
  70. {
  71. Integer ind = permEntry.getKey().ordinal();
  72. st.setObject(index + ind, permEntry.getValue(), SQL_TYPES[ind]);
  73. }
  74. }
  75. }
  76. @Override
  77. public Permissions deepCopy(Object value) throws HibernateException
  78. {
  79. if (value == null) return null;
  80. Permissions oldPerms = (Permissions) value;
  81. Permissions newPerms = new Permissions();
  82. for (Map.Entry&lt;PermissionType, Boolean&gt; permEntry : oldPerms.getPermissions().entrySet())
  83. {
  84. newPerms.setPermission(permEntry.getKey(), permEntry.getValue());
  85. }
  86. return newPerms;
  87. }
  88. @Override
  89. public boolean isMutable()
  90. {
  91. return false;
  92. }
  93. @Override
  94. public Serializable disassemble(Object value) throws HibernateException
  95. {
  96. return deepCopy(value);
  97. }
  98. @Override
  99. public Object assemble(Serializable cached, Object owner) throws HibernateException
  100. {
  101. return deepCopy(cached);
  102. }
  103. @Override
  104. public Object replace(Object original, Object target, Object owner) throws HibernateException
  105. {
  106. return deepCopy(original);
  107. }
  108. }
  1. And then use this custom basic type in your entity mapping:
  1. import org.hibernate.annotations.Columns;
  2. import org.hibernate.annotations.Type;
  3. @Entity
  4. @Table(name = &quot;user_type&quot;)
  5. public class UserTypeEntity
  6. {
  7. @Id
  8. @Column(name = &quot;id&quot;)
  9. private Long id;
  10. @Column(name = &quot;name&quot;)
  11. private String name;
  12. @Type(type = &quot;com.me.PermissionUserType&quot;)
  13. @Columns(columns = {
  14. // the order should be matched with the enum PermissionType
  15. @Column(name = &quot;can_create&quot;),
  16. @Column(name = &quot;can_edit&quot;),
  17. @Column(name = &quot;can_delete&quot;)
  18. })
  19. private Permissions permissions;
  20. // ...
  21. }

huangapple
  • 本文由 发表于 2020年9月20日 20:12:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63978845.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定