【问题标题】:Unable to insert in table using hibernate无法使用休眠插入表中
【发布时间】:2016-09-12 16:28:24
【问题描述】:

我正在使用休眠创建表,然后在应用程序启动时将记录插入表中。

为了插入记录,我使用this 页面的最后一个示例

问题: Hibernate 能够创建表,但是当我在应用程序启动时插入记录时,它没有被插入。

另一方面,如果我使用 REST 服务来完成相同的任务,它工作得非常好。

这是我的 JPA 课程。

package com.vizexperts.georbis.usermanagement.types;

import javax.persistence.*;

@Entity
public class TestMe {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long Id;

    @Column
    String name;

    public TestMe(String name) {
        this.name = name;
    }

    public Long getId() {
        return Id;
    }

    public void setId(Long id) {
        Id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

这里是对应的TestMeRepository类。

package com.vizexperts.georbis.usermanagement.types;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface TestMeRepository extends CrudRepository<TestMe, Long> {
    TestMe findByName(String name);
}

这就是我插入数据的方式。

package com.vizexperts.georbis.config;
import com.vizexperts.georbis.usermanagement.types.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public class InitialDataConfig  implements ApplicationListener<ContextRefreshedEvent>{
    @Autowired
    TestMeRepository testMeRepository;
    @Override
    public void onApplicationEvent(final ContextRefreshedEvent event) {
         // Here newly saved object is returned as testMe
         // when debugging i can see the auto generated **id** for 
         // testMe object.
         TestMe testMe = testMeRepository.save(new TestMe("Test"));
    }
}

正如我所说,如果我使用以下服务,它就可以工作。

@RequestMapping("/georbis/test")
    public Response<Void> test(){
        testMeRepository.save(new TestMe("working"));
        return new Response<>(true, "working");
    }

【问题讨论】:

  • 启动时有任何错误/异常吗?
  • 改用CommandLineRunner
  • @VinayVeluri 完全没有错误/异常。方法成功执行。即使save 方法返回testMe 对象,我可以看到新保存的对象自动生成id
  • @SanjayRawat 与CommandLineRunner 的情况相同,但表中没有任何内容。

标签: java spring hibernate jpa spring-boot


【解决方案1】:

我认为原因是您在 InitialDataConfig 类上缺少 @Component 注释。

这就是为什么这个类没有注册为 bean 并且永远不会调用 onApplicationEvent 方法的原因。

添加@Component 注释,它应该可以正常工作。

您也可以使用CommandLineRunner,试试这个example

【讨论】:

  • 我用了@Component注解只是忘了更新问题。表格中仍然没有插入任何内容。
  • 其实我就是这样使用CommandLineRunnernixmash.com/java/using-spring-boot-commandlinerunner
  • 还有onApplicationEventrun 方法,以防CommandLineRunner 都被调用。
  • 那很奇怪,你能把代码分享到 github 或任何其他网站吗?我会尝试找出问题所在,因为您正在做的似乎很好。
  • 好吧,我创建了一个单独的项目,这样我就可以将代码发送给您并猜测它在新项目中的工作原理,但在旧项目中却没有。
猜你喜欢
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2016-08-21
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多