javaspring-bootentitymanagerpostconstruct

How properly create entity in @PostConstruct?


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?


Solution

  • 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...
        }