简体   繁体   中英

Deserialize and persist with @ManyToMany

I have a Spring Boot app which is using MySQL db. At the moment I'm trying to do the following: - deserialize instances from the *.csv files; - inject them into the MySQL db.

For the simple instances there are no issues. But in case if I have an object with ManyToMany or OneToMany relations, deserialization is not working correctly. Currently I'm using Jackson dependency for *.csv deserialization:

    CsvMapper csvMapper = new CsvMapper();
    csvMapper.disable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
    CsvSchema csvSchema = csvMapper.schemaFor(type).withHeader().withColumnSeparator(';').withLineSeparator("\n");
    MappingIterator<Object> mappingIterator = csvMapper.readerFor(type).with(csvSchema).readValues(csv);

    List<Object> objects = new ArrayList<>();
    while (mappingIterator.hasNext()) {
        objects.add(mappingIterator.next());
    }

Example of the instance with many to many: (Idea is that one app can have different versions)

public class Application {

private Long id;
private String name;

@OneToMany(mappedBy = "application")
private Set<Version> versions = new HashSet<>();
}

For insertion into the DB I'm using Spring Boot entities that are @Autowired. My first question is - what should I put as an input into the CSV file to deserialize it correctly ? Because if I have :

id;name; 1;testName;

(skipping versions), I'm having a trouble. The same even if I try to put some values into the version. So I don't know how to provide correctly the input for Jackson CSV deserialization in case of SET + later, how can I persist this entity ? Should I first put all the versions into the DB and then try to put applications?

Any thoughts? Thanks in advance!

Use ApacheCommons to parse csv.

final byte[] sourceCsv;
String csvString = new String(sourceCsv);
CSVFormat csvFormat = CSVFormat.DEFAULT;
List<CSVRecord> csvRecord = csvFormat.parse(new 
StringReader(csvString)).getRecords();

It will help you to deserialize and to store in database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM