代码之家  ›  专栏  ›  技术社区  ›  Pilpin

Eclipselink-将列表转换为字符串(通过gson):持久化后,字符串无法更新

  •  0
  • Pilpin  · 技术社区  · 7 年前

    Payara 4.1.2.181(以及相应的eclipselink版本)

    大家好,

    我想将代表注释的实例列表存储为json字符串(作为字符串、用户id和日期),因此我使用属性转换器将列表转换为字符串:

    @Converter(autoApply = true)
    public class NotesAttributeConverter implements AttributeConverter<List<Note>, String> {
        private Gson gson = new Gson();
    
        @Override
        public String convertToDatabaseColumn(List<Note> notes) {
            return gson.toJson(notes);
        }
    
        @Override
        public List<Note> convertToEntityAttribute(String string) {
            return gson.fromJson(string, new TypeToken<List<Note>>(){}.getType());
        }
    }
    

    这是实体端的字段:

    @Column(name = "note", columnDefinition = "text")
    @Getter @Setter
    private List<Note> notes;
    

    我可以用注释很好地保存实体,问题是当我想要合并实体时,数据库上的“注释”字段永远不会更新:数据库字段永远不会更新,它甚至不会尝试合并实体,因为优化锁不会更改。

    你知道发生了什么事吗?我做错什么了吗?应该是这样还是一个bug?

    非常感谢。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Pilpin    7 年前

    我问 the same question on Eclipse's forums 得到了答案,或者更确切地说 这个 答复

    默认情况下,如所述 here ,该列表被eclipselink视为不可变的,这意味着您可以向列表中添加或删除内容,但只要您不将“新”列表分配给字段,eclipselink就不会尝试将其合并。 因此,要使其正常工作,您要么需要分配一个新列表,要么需要使用@Mutable对字段进行注释。

    新建列表示例:

    notes.add(newNote);
    notes = new ArrayList<>(notes);
    

    注释示例:

    @Mutable
    @Column(name = "note", columnDefinition = "text")
    @Getter @Setter
    private List<Note> notes;
    

    非常感谢eclipse论坛的ChrisDelahunt。