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

前端 未结 15 936
时光说笑
时光说笑 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:38

    Basically, you should add a specific unique field. I usually use xxxUri fields.

    class User {
    
        @Id
        // automatically generated
        private Long id;
    
        // globally unique id
        @Column(name = "SCN", nullable = false, unique = true)
        private String scn;
    }
    

    And you business method will do like this.

    public User findUserByScn(@NotNull final String scn) {
        CriteriaBuilder builder = manager.getCriteriaBuilder();
        CriteriaQuery criteria = builder.createQuery(User.class);
        Root from = criteria.from(User.class);
        criteria.select(from);
        criteria.where(builder.equal(from.get(User_.scn), scn));
        TypedQuery typed = manager.createQuery(criteria);
        try {
            return typed.getSingleResult();
        } catch (final NoResultException nre) {
            return null;
        }
    }
    

提交回复
热议问题