Hibernate 的国家/地区代表
我正在将 JDBC 项目迁移到 Hibernate。 我对数据库中存储的参考数据有疑问,特别是联合国国家/地区列表。 我从这里获取它。
当我使用 JDBC 时,我只有一个保存该数据的表,并且我曾经使用它来验证数据库中的数据。例如,用户无法输入他居住在该表中不存在的国家/地区。
现在,我有代表一个人的 Pojo,还有一个代表国家的字符串成员,我如何使用 Hibernate 持久化它,我需要为国家创建一个 Pojo 吗? 如何将下面的代码引用到不是 pojo 的“参考表”?
@OneToOne
@JoinColumn(name = "country_iso")
private String country;
上面的代码是我开始写的,但我不知道这是否是这样做的方法。
I'm in the process of migrating my JDBC project to Hibernate.
I have a question regarding reference data stored in my DB, in perticular it's the UN country list.
I took it from here.
When I was using JDBC, I just had a table that hold that data, and I used to use it to validate the data in the DB. for instance, a user couldn't enter that he lives in a country which didn't exist in that table.
Now, I have the Pojo that represents a person, and I have a string member which represents a country, how do I persist it with Hibernate, do I need to create a Pojo for country ?
How can I reference the below code to a "reference table" which isn't a pojo ?
@OneToOne
@JoinColumn(name = "country_iso")
private String country;
the above code, is what I started to write, but I don't know if this is the way to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为创建一个类
Country
是个好主意,使用 iso 代码作为 id。您需要建立多对一关系,因为一个国家/地区可以存在很多人。
Country:
Person:
这样,您可以使用 Hibernate 将所有国家/地区作为集合加载,并且可以为关系设置规则(例如可选 = false 等)
I think it's a good idea to create a class
Country
, using the iso code as id.You need to setup a many-to-one relation as many persons can exist in one country.
Country:
Person:
In that way, you can load all countries as a collection using Hibernate, and you can set up rules for the relation (like optional=false, etc)
我建议您为 Country 创建一个实体
,就像使用此映射一样,将 Country pojo 映射到表国家/地区,并将该实体设置为不可变并启用 2L 缓存(这是使用只读策略启用 2L 缓存的最佳情况)
I would suggest you create an entity for Country like
with this mapping, you map Country pojo to table countries, and also set this entity to immutable and enabled 2L cache as well (this is the best case to enable 2L cache with readonly strategy )
在这种情况下,您可以遵循以下方法。我假设您不会在运行时插入
Country
表。在
Person
类中有一个 CountryId 字段。当您要将
Person
保存到数据库时根据国家/地区名称(从数据库)获取countryId并将其设置为Person
的countryId。然后保存Person
。您可以为
Country
创建一个POJO,并在需要时在Person
类中引用它。In this type of situations you can follow the below approach. I am presuming that you will not be inserting the
Country
table at run-time.Have a field for countryId in the
Person
class.when you want to save the
Person
to the database get the countryId depending on the country name(from the database) and set it to countryId of thePerson
. Then save thePerson
.You can have a POJO for
Country
and refer it inPerson
class if need.