简体   繁体   English

JPA-从数据库查找表加载静态数据的最佳实践是什么?

[英]JPA - What's the best practice way to load static data from a Database lookup table?

I have a lookup table in my relational database schema called UserRole where it has the following table columns: 我在关系数据库架构中有一个名为UserRole的查找表,其中具有以下表列:

Role_Id | Role_Name | Role_Desc | (some other foreign key ids linking to other tables) |
-------------------------------------------------------------------------------
1       | Admin     | Admin user| ......                                               | 

All rows in above table are static data (they never ever change in my application) 上表中的所有行都是静态数据(它们在我的应用程序中从未更改)

At the moment i have an Entity persistent object: 目前,我有一个Entity持久对象:

@Entity
@Table(name = "UserRole")
public class RoleEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Role_Id")
private int id;

@Column(name = "Role_Name")
private String role_name;

@Column(name = "Role_Desc")
private String role_desc;
....

// other code omitted for brevity
}

I have an equivalent Repository class which just fetches the data: for eg 我有一个等效的Repository类,它只获取数据:例如

entityManager.find(...).getResultsList() etc... entityManager.find(...).getResultsList()等...

................................................................ ................................................... ..............

Every time when i need to use these roles i am making a call to the database directly. 每当我需要使用这些角色时,我都会直接调用数据库。 I feel there is no need for this because the data never change in my case. 我觉得没有必要这样做,因为在我的情况下数据永远不会改变。 I thought of storing the data in an Enum instead and not have that data in the database but the data is already part of a legacy system and i can't change the database design plus that table already has many links to other tables. 我想到了将数据存储在Enum中,而数据库中没有该数据,但是该数据已经是旧系统的一部分,并且我无法更改数据库设计,而且该表已经具有指向其他表的许多链接。

I want to load them only once maybe at startup. 我只想在启动时加载一次。

What is the best way to do this? 做这个的最好方式是什么?

Is it simply just have like a singleton class to maintain a (static?) list of all the roles, and after initialising, use the Repository class to make a call to Database to fetch the data into the list in memory.? 是否只是像单例类那样维护所有角色的(静态?)列表,并且在初始化之后,使用Repository类调用Database以将数据提取到内存中的列表中?

What worked for this particular problem is what OndrejM suggested. OndrejM建议的解决此特定问题的方法。 It as simply as creating a singleton bean and store results of my query upon startup. 就像创建一个单例bean并在启动时存储查询结果一样简单。 And of course, there is no pattern or official way to do it. 当然,没有任何模式或官方方式可以做到。 That is the answer. 那就是答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM