How do I embed a String Array into an Entity (JPA)

后端 未结 2 442
半阙折子戏
半阙折子戏 2021-01-24 11:13

I wanna design an Entity Class which has a String[] property. This String Array always has two values and I dont want Hibernate (or rather JPA) create an extra table for this bu

2条回答
  •  独厮守ぢ
    2021-01-24 11:27

    If there is always exactly two values, you can play with getter/setter and instance variable. You can indeed choose whether you map instance variable or property with @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];
    }
    

    Otherwise look at @Embedded entity. Something in the spirit of

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

提交回复
热议问题