代码之家  ›  专栏  ›  技术社区  ›  André Chalella

我可以使嵌入的休眠实体不可为空吗?

  •  31
  • André Chalella  · 技术社区  · 15 年前

    我想要什么:

    @Embedded(nullable = false)
    private Direito direito;
    

    但是,正如您所知,@embeddable没有这样的属性。

    有正确的方法吗?我不想要解决办法。

    5 回复  |  直到 8 年前
        1
  •  36
  •   ChssPly76    15 年前

    可嵌入组件(或复合元素,无论您想如何调用它们)通常包含多个属性,因此被映射到多个列。因此,可以用不同的方式处理整个为空的组件;J2EE规范没有规定任何一种方式。

    如果组件的所有属性都为空,则Hibernate将其视为空(反之亦然)。因此,可以将一个(任意)属性声明为非空(在 @Embeddable 或作为 @AttributeOverride @Embedded )实现你想要的。

    或者,如果您使用的是Hibernate验证程序,则可以使用注释属性 @NotNull 虽然这只会导致应用程序级别检查,而不是数据库级别。

        2
  •  15
  •   user158037    8 年前

    可以使用“hibernate.create_empty_composites.enabled”来更改此行为(请参见 https://hibernate.atlassian.net/browse/HHH-7610 )

        3
  •  11
  •   TomáÅ¡ Záluský    14 年前

    将虚拟字段添加到标记为@embeddable的类中。

    @Formula("0")
    private int dummy;
    

    https://issues.jboss.org/browse/HIBERNATE-50 .

        4
  •  1
  •   Eric B.    10 年前

    我对之前提出的任何一个建议都不太兴奋,所以我创建了一个可以为我处理这个问题的方面。

    这还没有完全测试过,而且绝对没有针对嵌入对象集合进行测试,所以买家要小心。不过,到目前为止似乎对我有用。

    基本上,截取吸气剂到 @Embedded 字段并确保字段已填充。

    public aspect NonNullEmbedded {
    
        // define a pointcut for any getter method of a field with @Embedded of type Validity with any name in com.ia.domain package
        pointcut embeddedGetter() : get( @javax.persistence.Embedded * com.company.model..* );
    
    
        /**
         * Advice to run before any Embedded getter.
         * Checks if the field is null.  If it is, then it automatically instantiates the Embedded object.
         */
        Object around() : embeddedGetter(){
            Object value = proceed();
    
            // check if null.  If so, then instantiate the object and assign it to the model.
            // Otherwise just return the value retrieved.
            if( value == null ){
                String fieldName = thisJoinPoint.getSignature().getName();
                Object obj = thisJoinPoint.getThis();
    
                // check to see if the obj has the field already defined or is null
                try{
                    Field field = obj.getClass().getDeclaredField(fieldName);
                    Class clazz = field.getType();
                    value = clazz.newInstance();
                    field.setAccessible(true);
                    field.set(obj, value );
                }
                catch( NoSuchFieldException | IllegalAccessException | InstantiationException e){
                    e.printStackTrace();
                }
            }
    
            return value;
        }
    }
    
        5
  •  1
  •   Dominik Hadl    10 年前

    可以使用NullSafe getter。

    public Direito getDireito() {
        if (direito == null) {
            direito = new Direito();
        }
        return direito;
    }
    
    推荐文章