JPA初始化数据的最佳方法是什么? [英] What is the best way to initialize data by JPA?

查看:588
本文介绍了JPA初始化数据的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人通过将代码添加到某些初始化类的静态构造函数或类似的东西来初始化数据吗?我不知道这样的可能性在哪里:

Does anyone initialize data by putting some code to static constructor of some initailizing class or something like that? I wonder where is posibillity like this:

@EJB //some bean
public someDataClassOrFacade {
  static {
    if(DataFacade.checkIfThereIsNoExampleData()) {
     SomeDataClass sdc = new SomeDataClass();
     // (...) set data
     DataFacade.create(sdc);
    }
   }
} 

您如何看待这种初始化数据的方式?我不相信将SQL查询与maven SQL插件一起使用,因为它的灵活性很低(假设数据结构可以更改,尤其是列名).但是,我不太确定何时加载类.但这只是我的理论实践,也许您正在使用比这更好的东西?谢谢.

What do you think about this way to initialize data? I am not convinced about using SQL queries with maven SQL plugin, because it has low flexibility (assuming data structure can change, especially columns names). But, i not pretty sure when class will be loaded. But this is only my theoretical practice, maybe you're using something far better than that? Thanks.

推荐答案

在我看来,您希望在控制的时间内尽可能晚地初始化数据,因此静态初始化器对我来说是不行的.这取决于我在哪里进行初始化的应用程序类型.如果存在Web层,我可能会使用特定于Web框架的初始化方法或Servlet上下文侦听器来实现.如果只有EJB层,我可以在带有@Startup注释的单例EJB中进行操作,因为我快速搜索过的该线程显示:

You want to initialize the data as late as possible and in a controlled moment in my opinion, so static initializers are a no-no for me. It depends on what type of application it is where I would do the initialization. If there is a web layer I would probably do it with a web framework specific initialization method or with a servlet context listener. If there is only an EJB layer, I might do it in a singleton EJB annotated with @Startup as this thread I quick-googled shows:

EJB无状态-私有成员初始化

这篇关于JPA初始化数据的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆