0

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

1 Answer 1

1

I want to avoid to iterate manually through all files, getting the format and check if it already exists.

With your current model this is exactly what you need to do: instead of creating a new Format load it and only when that fails create a new instance. I honestly don't see why it seems so important to you to not do that since it seems like a rather trivial line of code or two.

An alternative would be to map Format as an embedded. Here is a little tutorial about that concept if you need it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.