I've got an issue regarding saving child objects with Spring Hibernate and hope you can give me a hint. Already searched on Stackoverflow, but I couldn't find anything for my use case.
I have two classes:
Class File {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "format_id")
private Format format;
}
Class Format {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "puid")
private String puid;
}
When I read a given XML file..
<files>
<file>
<name>abc</name>
<format>pdf</format>
</file>
<file>
<name>xyz</name>
<format>pdf</format>
</file>
</files>
.. I create objects of class file and format accordingly. At the end I'll call fileRepository.savaAll();
My problem is, that now I have two formats in my mySQL database, although there are the same. Is there a way (perhaps through annotations) to only create new database elements for child elements, if not exists (puid should be unique).
I want to avoid to iterate manually through all files, getting the format and check if it already exists.
Thanks