簡體   English   中英

使用 hibernate 保留集合字段

[英]Persist collection fields with hibernate

使用 hibernate,如何使用List<String>字段保留 class?

考慮以下實體 class:

@Entity
public class Blog {
    private Long id;
    private List<String> list;

    @Id
    @GeneratedValue
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public List<String> getList() { return list; }
    public void setList(List<String> list) { this.list = list; }
}

但是,當我嘗試保存它時,出現以下錯誤:

[INFO] An exception occured while executing the Java class. null

Could not determine type for: java.util.List, at table: Blog, for columns: [org.hibernate.mapping.Column(list)]

我嘗試將“ @CollectionOfElements ”添加到getList() ,但隨后只有id被保存到庫中。 沒有為列表創建相應的列。

注意:我只是嘗試 Hibernate,所以我可以使用文檔鏈接,我們將幫助我了解 Hibernate 中的收集關系管理

看看這個 也許它有所幫助。

您是否按如下方式應用@CollectionOfElements?

@org.hibernate.annotations.CollectionOfElements(
targetElement = java.lang.String.class

看看關於集合Hibernate Annotations文檔,基本上你必須告訴列表它與它的關系。

@OneToMany(mappedBy="blog")
public List<String> getList() { return list; }

然后它應該工作。

使用Serializable對象似乎更好。 list屬性更改為ArrayList<String>似乎可以解決問題。

 package com.company.directDataLoader.model.admin;

import java.util.Arrays;
import java.util.Collection;
import javax.persistence.AttributeConverter;

import static java.util.Collections.emptyList;

public class StringListConverter implements AttributeConverter<Collection<String>, String> {
    private static final String SPLIT_CHAR = ";";

    @Override
    public String convertToDatabaseColumn(Collection<String> stringList) {
        return stringList != null ? String.join(SPLIT_CHAR, stringList) : "";
    }

    @Override
    public Collection<String> convertToEntityAttribute(String string) {
        return string != null ? Arrays.asList(string.split(SPLIT_CHAR)) : emptyList();
    }
}

在實體 class 中:

@Column(name="table_keys")
@Convert(converter = StringListConverter.class)
private Collection<String> tableKeys;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM