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

2020-04-30 01:43发布

问题:

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 but embed this two String values directly into the table. Is this possible and if so how?

回答1:

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;
}


回答2:

If this array always has two elements, why not simply create a class to hold them and than map that class as Component?