hibernate - How to map an ArrayList of primitives to a single column? -
let's have following situation:
object car has arraylist of prices, numbers. possible in hibernate save prices in single column? know violates first normal form there might cases when don't want them saved in separate table it's classically done in one-to-many or many-to-many relationships.
in jdo i'd saving arraylist in blob column.
some useful related sof questions: arraylist of primitive types in hibernate , map arraylist hibernate .
any idea highly appreciated!
i know old question trying in jpa context can this
import org.apache.commons.lang3.stringutils; import javax.persistence.attributeconverter; import javax.persistence.converter; import java.util.arraylist; import java.util.arrays; import java.util.list; import java.util.stream.collectors; import java.util.stream.stream; @converter public class intarraytostringconverter implements attributeconverter<list<integer>,string>{ @override public string converttodatabasecolumn(list<integer> attribute) { return attribute == null ? null : stringutils.join(attribute,","); } @override public list<integer> converttoentityattribute(string dbdata) { if (stringutils.isblank(dbdata)) return new arraylist<>(); try (stream<string> stream = arrays.stream(dbdata.split(","))) { return stream.map(integer::parseint).collect(collectors.tolist()); } } }
then use in entity
@entity public class someentity { @id @generatedvalue(strategy = generationtype.identity) private integer id; @column @convert(converter = intarraytostringconverter.class) private list<integer> integers; ... }
enjoy !!!
Comments
Post a Comment