JPA: How to get entity based on field value other than ID?

前端 未结 15 943
时光说笑
时光说笑 2020-12-04 21:08

In JPA (Hibernate), when we automatically generate the ID field, it is assumed that the user has no knowledge about this key. So, when obtaining the entity, user would query

15条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 21:37

    Best practice is using @NaturalId annotation. It can be used as the business key for some cases it is too complicated, so some fields are using as the identifier in the real world. For example, I have user class with user id as primary key, and email is also unique field. So we can use email as our natural id

    @Entity
    @Table(name="user")
    public class User {
      @Id
      @Column(name="id")
      private int id;
    
      @NaturalId
      @Column(name="email")
      private String email;
    
      @Column(name="name")
      private String name;
    }
    

    To get our record, just simply use 'session.byNaturalId()'

    Session session = sessionFactory.getCurrentSession();
    User user = session.byNaturalId(User.class)
                       .using("email","huchenhai@qq.com")
                       .load()
    

提交回复
热议问题