有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java查找hibernate实体列(字段成员)是否在运行时为空

我有一个问题,我想发现hibernate实体的字段(byentityClass)是否表示可空列

然而,我希望使用可靠的hibernate meta来获得它,而不是像检查@NotNull注释一样,尝试覆盖hibernate的任何可能场景,考虑实体字段是否为空似乎不是非常可靠

谢谢你的帮助


共 (1) 个答案

  1. # 1 楼答案

    感谢@krokodilko,我提供了解决方案代码:

    protected SessionFactory getSessionFactory() {
        return getEntityManager().getEntityManagerFactory().unwrap(SessionFactory.class);
    }
    

    获取可为空的元数据

    Map<String, Boolean> entityPropNullables = new HashMap<String, Boolean>();
    // Provide the class of disired metadata as parameter
    ClassMetadata entityMeta = getSessionFactory().getClassMetadata(anEntityClass);
    String[] propNames = entityMeta.getPropertyNames();
    boolean[] isNullableProps = entityMeta.getPropertyNullability();
    
    if (propNames != null) {
        for (int i = 0; i < propNames.length; i++ ) {
            entityPropNullables.put(propNames[i], isNullableProps[i]);
        }
    }