如何在@postConstruct中正确创建实体?

发布于 2025-02-02 02:12:06 字数 517 浏览 1 评论 0原文

我尝试在Springboot应用中@PostConstruct中创建一些实体

    @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);
}

,我有错误分离的实体传递给了持久:com.amr.project.model.entity.image;

我尝试添加 @transactional @transactional不要与@postconstrcut一起使用,并且不起作用。

我如何正确创建实体?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挥剑断情 2025-02-09 02:12:06

正如I_AM_PAUL评论的那样,JPA实体不是弹簧bean,因此@PostConscont永远不会被调用。
尝试使用@preload JPA注释

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

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...
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文