简体   繁体   English

如何检查对象是否已保存到数据库

[英]How to check if object have been saved to database

I am using Spring JDBC and I want to create a method which checks if it have been persisted to the database yet or not, meaning that would have gotten an auto incremented key. 我正在使用Spring JDBC,我想创建一个方法来检查它是否已经持久存储到数据库,这意味着它将获得一个自动递增的密钥。

I have a field named id of type int. 我有一个名为id的类型为int的字段。 Since primitive ints are auto assigned 0 if no other values is given I could create a method that checks if id == 0 but then I must ensure that my primary key sequences starts on 1. 由于如果没有给出其他值,则原始int被自动分配为0我可以创建一个方法来检查id == 0但是我必须确保我的主键序列从1开始。

I could also create a method in the repository to check if the object was saved, however I do not want to do a query for this. 我还可以在存储库中创建一个方法来检查对象是否已保存,但是我不想对此进行查询。

Last option that I could think of was to change the type of the id to Integer and then check if it was null but I don't know if that is a good way to do it. 我能想到的最后一个选项是将id的类型更改为Integer ,然后检查它是否为null但我不知道这是否是一个很好的方法。

Are there a way to have a method in the domain layer to do this? 有没有办法在域层中使用方法来执行此操作?

Changing the type of id from int to Integer is considered a good idea: persistence frameworks such as Hibernate and JPA encourage it (see this example from java.net and this one from adam-bien.com ). id的类型从int更改为Integer被认为是一个好主意: Hibernate和JPA等持久性框架鼓励它(参见java.net中的这个例子和adam-bien.com的这个例子)。

Using an object type allows you to quickly tell an unpersisted object from a persisted one just by checking whether id == null . 使用对象类型允许您通过检查id == null来快速告知持久化对象。 Just for completeness: 只是为了完整性:

  • id == null : unsaved object, perform an INSERT id == null :未保存的对象,执行INSERT
  • id != null : object already saved, perform an UPDATE id != null :对象已保存,执行UPDATE

This way, you don't have to treat 0 (or any other integer value) as a special case meaning uninitialized ; 这样,您不必将0 (或任何其他整数值)视为意味着未初始化的特殊情况; you already have null , which communicates nicely the idea of special case. 你已经有了null ,它很好地传达了特殊情况的想法。

Adding a business key 添加业务键

An even better approach, suggested in this article , is to use a business key in additon to the database-managed ID. 本文中建议的更好的方法是在数据库管理的ID中添加业务键。 The business key is an entity identifier which, unlike the auto-generated primary key ( surrogate key ), has some meaning to the user ( natural key ). 业务密钥是实体标识符,与自动生成的主键( 代理键 )不同,它对用户具有一些含义( 自然键 )。

You should then override the equals method to compare two objects using the business key, and not the auto-generated primary key. 然后,您应该覆盖equals方法以使用业务键比较两个对象,而不是自动生成的主键。

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

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