简体   繁体   中英

JPA Hibernate - How to create a table from an array of strings “String[]”

I have the following entity which works fine and stores all columns in a table for newapplicationmodel, but I want private String[] emails to be it's own entity/table (similar to @OneToMany, but @OneToMany is looking for an array of objects that have key/values. I just have the string value)

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class newapplicationmodel {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="applicationid")
    private Long applicationid;

    @Column(name="propertyid")
    private String propertyid;

    @Column(name="moveindate")
    private String moveindate;

    private String[] emails;

}

You can use a Set or a List instead of an Array and Annotate this with @ElementCollection.
This will generate a Table named "newapplicationmodel_emails" containing the emails.
You can change the table name with a additional @CollectionTable(name="someName")

A few Links:
https://javaee.github.io/javaee-spec/javadocs/javax/persistence/ElementCollection.html
https://javaee.github.io/javaee-spec/javadocs/javax/persistence/CollectionTable.html
https://en.wikibooks.org/wiki/Java_Persistence/ElementCollection#Basic_Collections

You need @ElementCollection to save emails in a separate table

@ElementCollection
@CollectionTable(name = "emails", joinColumns = @JoinColumn(name = "applicationid"))
//where table name is "emails" and join column name is "applicationid"
@Column(name = "email")
private Set<String> emails = new HashSet<>();

Another approach is to use @Converter and save the emails list as a comma-separated text

@Column(name = "emails")
@Convert(converter = EmailsToStringConverter.class)
private List<String> emails;

@Converter
public class EmailsToStringConverter implements AttributeConverter<List<String>,String>{
    @Override
    public String convertToDatabaseColumn(List<String> attribute) {
        return attribute == null ? null : StringUtils.join(attribute, ",");
    }

    @Override
    public List<String> convertToEntityAttribute(String columnValue) {
        if (StringUtils.isBlank(columnValue)) {
            return Collections.emptyList();
        }

        return Arrays.asList(columnValue.split(","));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM