如何在不创建新表的情况下映射Set<Date>日期?

huangapple 未分类评论46阅读模式
英文:

How can I map Set<Date> dates without creating a new table?

问题

@Entity(name = "my_entity_name")
public class MyEntityName {
    
    /* 一些普通的字段 */

    private Set<Date> dates = new HashSet<>();
   
    /* 所有字段的Getter和Setter */
}
我想将这个日期集合以单列的形式保存对我来说可以使用JSON),保存在同一个实体中在JPA中是否有此解决方案请帮助我...提前谢谢
英文:
@Entity(name = &quot;my_entity_name&quot;)
public class MyEntityName {
    
    /* some normal fields */

    private Set&lt;Date&gt; dates = new HashSet&lt;&gt;();
   
    /* Getters and setters for all fields */
}

I want to save this collection of dates as a single column (as json is ok for me) in this same entity. Is there any solution for this in JPA? Please help me... thanks in advance.

答案1

得分: 0

你应该为此目的使用String字段。
集合通常与@ManyToMany或@OneToMany映射一起使用。

英文:

You should probably use String field for that purpose.
Sets are used mostly with mapping @ManyToMany or @OneToMany

答案2

得分: 0

我通过在实体类中的集合类型字段上使用@Converter(converter = MyCustomTypeConverter.class)来获得解决方案。

示例转换器将如下所示:

public class MyCustomTypeConverter implements AttributeConverter<Set<Date>, String> {

    private ObjectMapper mapper = new ObjectMapper();
    
    @Override
    public String convertToDatabaseColumn(Set<Date> attribute) {
        
        //将集合字段转换为字符串的代码
    }

    @Override
    public Set<Date> convertToEntityAttribute(String dbData) {
        
        //将数据库字符串字段转换为集合字段的代码
    }
}
英文:

I got the solution by using @Converter(converter = MyCustomTypeConverter.class) on the collection type field in my entity class.

sample converter will look like this

public class MyCustomTypeConverter implements AttributeConverter&lt;Set&lt;Date&gt;, String&gt; {

    private ObjectMapper mapper = new ObjectMapper();
    
    @Override
    public String convertToDatabaseColumn(Set&lt;Date&gt; attribute) {
        
        //code to convert from collection field to string
    }

    @Override
    public Set&lt;Date&gt; convertToEntityAttribute(String dbData) {
        
        //code to convert from db-string field to collection field.
    }
}

huangapple
  • 本文由 发表于 2020年5月4日 02:29:48
  • 转载请务必保留本文链接:https://java.coder-hub.com/61579629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定