【问题标题】:How do I embed a String Array into an Entity (JPA)如何将字符串数组嵌入实体 (JPA)
【发布时间】:2011-01-20 11:21:55
【问题描述】:

我想设计一个具有 String[] 属性的实体类。这个字符串数组总是有两个值,我不希望 Hibernate(或者更确切地说 JPA)为此创建一个额外的表,而是将这两个字符串值直接嵌入到表中。 这可能吗?如果可以,怎么办?

【问题讨论】:

    标签: java hibernate jpa arrays entity


    【解决方案1】:

    如果总是恰好有两个值,您可以使用 getter/setter 和实例变量。您确实可以选择是否使用@Column 映射实例变量或属性。

    @Column
    String s1;
    
    @Column
    String s2;
    
    public String[] getProp()
    {
      return new String[]{ s1, s2 };
    }
    
    public String setProp(String[] s )
    {
       s1 = s[0];
       s2 = s[1];
    }
    

    否则查看@Embedded 实体。有精神的东西

    @Entity
    public class MyEntity {
    
        @Embedded
        public StringTuple tuple;
    
    }
    
    public class StringTuple {
        public String s1;
        public String s2;
    }
    

    【讨论】:

      【解决方案2】:

      如果这个数组总是有两个元素,为什么不简单地创建一个类来保存它们,然后将该类映射为Component

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-29
        • 1970-01-01
        • 2010-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-07
        • 2016-08-16
        相关资源
        最近更新 更多