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

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

    In my Spring Boot app I resolved a similar type of issue like this:

    @Autowired
    private EntityManager entityManager;
    
    public User findByEmail(String email) {
        User user = null;
        Query query = entityManager.createQuery("SELECT u FROM User u WHERE u.email=:email");
        query.setParameter("email", email);
        try {
            user = (User) query.getSingleResult();
        } catch (Exception e) {
            // Handle exception
        }
        return user;
    }
    

提交回复
热议问题