0

I try to create some entity in @PostConstruct in my SpringBoot app

    @PostConstruct
    void load() {
        for (int i = 0; i < 10; i++) {
            Item item = new Item();
            item.setRating(Math.random());
            imageList.add(new Image());
            item.setImages(imageList);
            itemRepository.save(item);
}

I have error detached entity passed to persist: com.amr.project.model.entity.Image;

I tried adding @Transactional but i find that @Transactional dont work with @PostConstrcut and it`s dont work.

How i can create entity properly?

Ashish Patil
  • 4,428
  • 1
  • 15
  • 36

1 Answers1

0

As I_AM_PAUL commented, JPA Entities are not Spring beans, so @PostConstruct won't ever be called. Try using @PreLoad JPA annotation

    @PreLoad
    void load() {
        for (int i = 0; i < 10; i++) {
            Item item = new Item();
            // And so on...
    }
Roman
  • 181
  • 7