SpringData 簡單的條件查詢

今天在寫springdata條件查詢時,JpaRepository的findOne方法,不知道是由於版本的緣由仍是其餘緣由,老是查詢不出來數據spring

  //springdata jpa版本爲1.5.15,配置1.5.18的springboot版本
  public
User getUserByEmail(String email){ User u=new User(); u.setUserEmail(email); Example<User> example=Example.of(u); User admin=null; admin=userRepository.findOne(example); return admin; }

另外,在以前用SpringBoot2.0版本時springboot

Optional<User> admin=userRepository.findOne(example);

admin.isPresent()的值也爲false,也取不到值!spa

解決辦法:SpringData的簡單查詢方法3d

1.在JpaRepository下添加方法

package com.fdzang.mblog.repository; import com.fdzang.mblog.pojo.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User,String> { User getByUserEmail(String userEmail); }

2.在service下使用該方法

package com.fdzang.mblog.service; import com.fdzang.mblog.pojo.User; import com.fdzang.mblog.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired UserRepository userRepository; /** * 經過郵箱獲得用戶信息 * @param email * @return
     */
    public User getUserByEmail(String email){ User admin=null; admin=userRepository.getByUserEmail(email); return admin; } }

3.總結

直接在接口中定義查詢方法,若是是符合規範的,能夠不用寫實現,目前支持的關鍵字寫法以下:

4.查詢方法解析

 

 5.使用@Query註解

 

 

相關文章
相關標籤/搜索