如何从jpa存储库更改方法名称?

时间:2018-11-15 08:46:21

标签: spring spring-data-jpa repository

spring + jpa(存储库)上有应用程序 实体:

@Entity
@Getter
@Setter
@NoArgsConstructor
public class User{
  private int id;
  private String name;
  private String surname;
  private int age;
}

因此,我的存储库如下所示:

@Repository
public interface UserRepository extends CrudRepository<User, Integer>{
  public List<User> findUsersByNameAndAge(String name, int age);
  public List<User> findUsersByNameAndSurname(String name, String surname);
}

在我的实际产品代码中,参数太多,因此此方法名称太长且不舒适。 有没有办法从长方法名中选择合适的选项,例如find?

1 个答案:

答案 0 :(得分:3)

使用默认 Java 8包装功能:

例如:

   interface UserRepository extends JpaRepository<User, Long> {
  // don't use that crazy long method! use getByEmail instead
  User findFirstByEmailContainsIgnoreCaseAndField1NotNullAndField2NotNullAndField3NotNullAndField4NotNullAndField5NotNullAndField6NotNull(final String email);

  default User getByEmail(final String email) {
    return findFirstByEmailContainsIgnoreCaseAndField1NotNullAndField2NotNullAndField3NotNullAndField4NotNullAndField5NotNullAndField6NotNull(email);
  }
}

您可以在此处找到完整的参考:https://github.com/daggerok/spring-data-examples/blob/master/shadov/src/main/java/daggerok/ShadovApplication.java

否则,您可以为方法指定任何名称,并添加带有参数值的注释 @Query ,这样可以将所需的查询保存到数据库中,如下所示:

@Query(value="select u from User u where u.deleted=false and u.email=:email")
User findOneByEmail(@Param("email")String email);
or, with native sql query:

@Query(value="SELECT * FROM users WHERE deleted=false AND email=?1", nativeQuery=true)
User findOneByEmail(String email);

您还可以对查询使用遵循命名约定的名称,因为@Query注释将优先于方法名中的查询。