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

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

    Using CrudRepository and JPA query works for me:

    import org.springframework.data.jpa.repository.Query;
    import org.springframework.data.repository.CrudRepository;
    import org.springframework.data.repository.query.Param;
    
    public interface TokenCrudRepository extends CrudRepository {
    
     /**
     * Finds a token by using the user as a search criteria.
     * @param user
     * @return  A token element matching with the given user.
     */
        @Query("SELECT t FROM Token t WHERE LOWER(t.user) = LOWER(:user)")
        public Token find(@Param("user") String user);
    
    }
    

    and you invoke the find custom method like this:

    public void destroyCurrentToken(String user){
        AbstractApplicationContext context = getContext();
    
        repository = context.getBean(TokenCrudRepository.class);
    
        Token token = ((TokenCrudRepository) repository).find(user);
    
        int idToken = token.getId();
    
        repository.delete(idToken);
    
        context.close();
    }
    

提交回复
热议问题