【问题标题】:Access entity id inside Hibernate Usertype在 Hibernate Usertype 中访问实体 ID
【发布时间】:2017-09-24 07:52:06
【问题描述】:

我创建了自己的休眠用户类型实现类,它按预期工作。

我现在有一个要求,我需要在我的 Hibernate UserType 实现类中访问特定实体记录(通过序列生成)的“id”字段的值。有没有可能做到这一点?

下面是我的 UserType 实现:

    public class SecureStringType implements UserType {

        @Override
        public int[] sqlTypes() {
            return new int[] { Types.VARCHAR };
        }
        @Override
    public Class returnedClass() {
        return SecureString.class;
    }

    @Override
    public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
            throws SQLException {

        String encryptedValue = rs.getString(names[0]);

        getDataSecurityService().getActualValue(encryptedValue);
        SecureString secureString = new SecureString();
        secureString.setActualValue(decryptedValue);
        return secureString;
    }

    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
            throws SQLException {
        if (value == null) {
            st.setNull(index, Types.VARCHAR);
        } else {
            SecureString actualValue = (SecureString) value;
            st.setString(index, getDataSecurityService().encrypt(actualValue ));
        }
    }

// DeepCopy, disassemble, assemble method implementations
    }

我注意到 SharedSessionContractImplementorPersistentContext 里面有所有已加载实体的列表,但我没有办法确定正在调用 UserType 的实体。

`session.getPersistenceContext().getEntitiesByKey();` has all the `EntityKey` objects  but I need to get the one for which this `UserType` is being called currently.

有什么想法吗?

【问题讨论】:

  • 请出示代码
  • @Ndumiso 这真的需要代码吗?它可以是 Hibernate UserType 接口的任何实现。在该实现中,我需要访问我的实体的 id 字段
  • “我已经创建了我自己的hibernate UserType 实现类”,如果它和你的Entity类一样,那么你可以很容易的说,UserType ut; 然后ut.getId(); or ,ut.setId(id);
  • @Ndumiso 添加代码
  • @RezaPayambari 我不明白你在说什么。 UserType 是 Hibernate 提供的接口,它的实现与实体本身是分开的

标签: java hibernate jpa jakarta-ee


【解决方案1】:

我在我的代码库中遇到了同样的问题。 AFAIK,迄今为止我能找到的唯一选择是在 SecureString 类型中添加一个 ID 字段,在 @PreUpdate/@PreLoad 或其他回调期间设置它,或者在 getter 和 setter/constructors 中设置它,或者使用 HibernateInterceptor 在任何位置设置它适合您的生命周期。然后,您可以使用 value.getId() 或其他东西在 nullSafeSet 中访问它。它很疯狂,但它确实有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多