英文:
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 = "my_entity_name")
public class MyEntityName {
/* some normal fields */
private Set<Date> dates = new HashSet<>();
/* 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<Set<Date>, String> {
private ObjectMapper mapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(Set<Date> attribute) {
//code to convert from collection field to string
}
@Override
public Set<Date> convertToEntityAttribute(String dbData) {
//code to convert from db-string field to collection field.
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论