What is a natural identifier in Hibernate?

泪湿孤枕 提交于 2019-11-30 03:16:26

In Hibernate, natrual keys are often used for lookups. You will have an auto-generated surrogate id in most cases. But this id is rather useless for lookups, as you'll always query by fields like name, social security number or anything else from the real world.

When using Hibernate's caching features, this difference is very important: If the cache is indexed by your primary key (surrogate id), there won't be any performance gain on lookups. That's why you can define a set of fields that you are going to query the database with - the natural id. Hibernate can then index the data by your natural key and improve the lookup performance.

See this excellent blog post for a more detailed explanation or this RedHat page for an example Hibernate mapping file.

What naturally identifies an entity. For example, my email address.

However, a long variable length string is not an ideal key, so you may want to define a surrogate id

AKA Natural key in relational design

A natural identifier is something that is used in the real world as an identifier. An example is a social security number, or a passport number.

It is usually a bad idea to use natural identifiers as keys in a persistence layer because a) they can be changed outside of your control, and b) they can end up not being unique due to a mistake elsewhere, and then your data model can't handle it so your application blows up.

In a relational database system, typically, you can have two types of simple identifiers:

  • Natural keys, which are assigned by external systems and guaranteed to be unique
  • Surrogate keys, like IDENTITY or SEQUENCE which are assigned by the database.

The reason why Surrogate Keys are so popular is that they are more compact (4 bytes or 8 bytes), compared to a Natural Key which is very long (e.g. the VIN takes 17 alphanumerical characters, the book ISBN is 13 digits long).

Now, if the Surrogate Key becomes the Primary Key, you mao it using the JPA @Id annotation.

And, if you have an entity that has also a Natural Key, besides the Surrogate one, you can map it with the Hibernate-specific @NaturalId annotation:

@Entity(name = "Post")
@Table(name = "post")
public class Post {

    @Id
    @GeneratedValue
    private Long id;

    private String title;

    @NaturalId
    @Column(nullable = false, unique = true)
    private String slug;

    //Getters and setters omitted for brevity

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) 
            return false;
        Post post = (Post) o;
        return Objects.equals(slug, post.slug);
    }

    @Override
    public int hashCode() {
        return Objects.hash(slug);
    }
}

Now, considering the entity above, the user might have bookmarked a Post article and now they want to read it. However, the bookmarked URL contains the slug Natural Identifier, not the Primary Key.

So, we can fetch it like this using Hibernate:

Post post = entityManager.unwrap(Session.class)
.bySimpleNaturalId(Post.class)
.load(slug); 

And Hibernate will execute the following two queries:

SELECT p.id AS id1_0_
FROM post p
WHERE p.slug = 'high-performance-java-persistence'

SELECT p.id AS id1_0_0_,
       p.slug AS slug2_0_0_,
       p.title AS title3_0_0_
FROM post p
WHERE p.id = 1

The first query is needed to resolve the entity identifier associated with the provided natural identifier.

The second query is optional if the entity is already loaded in the first or the second-level cache.

As I explained in this article, the reason for having the first query is because Hibernate already has a well-established logic for loading and associating entities by their identifier in the Persistence Context.

Now, if you want to skip the entity identifier query, you can easily annotate the entity using the @NaturalIdCache annotation:

@Entity(name = "Post")
@Table(name = "post")
@org.hibernate.annotations.Cache(
    usage = CacheConcurrencyStrategy.READ_WRITE
)
@NaturalIdCache
public class Post {

    @Id
    @GeneratedValue
    private Long id;

    private String title;

    @NaturalId
    @Column(nullable = false, unique = true)
    private String slug;

    //Getters and setters omitted for brevity

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) 
            return false;
        Post post = (Post) o;
        return Objects.equals(slug, post.slug);
    }

    @Override
    public int hashCode() {
        return Objects.hash(slug);
    }
}

This way, you can fetch the Post entity without even hitting the database. Cool, right?

A social security number might be a natural identity, or as you've said a hash of the User's information. The alternative is a surrogate key, for example a Guid/UID.

Natural identifier (also known as business key): is an identifier that means or represent something in real life.
Email or national id for person
Isbn for Book
IBAN for Bank account

This @NaturalId Annotation is used to specify Natural identifier.

In relational database theory a relation can have multiple candidate keys. A candidate key is a set of attributes of a relation that are never duplicate in two rows of that relation and that cannot be reduced by removing one of the attributes and still guarantee uniqueness.

A natural ID is essentially a candidate key. Where "natural" means it is in the nature of the data you hold in that relation, not something you add like an autogenerated key. A natural ID can be composed of a single attribute. In general any attribute of a relation that is unique and not-null is a candidate key, and can be considered a natural id.

In Hibernate this annotation can be used simply to denote that an attribute can be used to do searches that return unique results while not using the key. This can be useful when the attribute you denote as natural id is more natural to deal with for you, e.g. when the actual key is autogenerated and you don't want to use in searches.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!