我有一个带有Spring Data JPA和两个映射到数据库的实体的Spring Boot应用程序。我的应用程序设置为在每次启动时重新创建数据库。现在,我想创建这些POJO的一些实例,并将其保存在数据库中,以便在进行中的开发过程中有一些数据可以测试我的应用程序。
最好的方法是什么?
到目前为止,我尝试过:我的班级添加示例数据
public class DBSampleAdditor {
@PersistenceContext
private EntityManager em;
@Transactional
public void addSampleData() {
// creating POJO instances and persist them with em.perists()
}
}
我试图在我的ApplicationClass的主体中调用这些函数
@SpringBootApplication()
public class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
DBSampleAdditor dbsa = new DBSampleAdditor();
dbsa.addSampleData();
}
}
这根本没有用,因为EntityManager从未从持久性单元获取实例。
我还尝试创建一个CommandLineRunner:
@Component
public class PTCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Adding sample data...");
DBSampleAdditor dbsa = new DBSampleAdditor();
dbsa.addSampleData();
}
}
但是在启动过程中似乎从未调用过该程序。
您可以将@PostConstruct和@Component一起使用,以在启动时插入数据。
在创建bean,注入依赖项,设置所有托管属性以及将bean实际设置为作用域之前,将调用@PostConstruct。
只需将您的数据库存储库注入标有@Component的类中,并在标有@PostConstruct的方法内调用注入的数据库存储库
例:
@Component
public class DbInit {
@Autowired
private UserRepository userRepository;
@PostConstruct
private void postConstruct() {
User admin = new User("admin", "admin password");
User normalUser = new User("user", "user password");
userRepository.save(admin, normalUser);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句