SpringData 簡單的條件查詢


今天在寫springdata條件查詢時,JpaRepository的findOne方法,不知道是因為版本的原因還是其他原因,總是查詢不出來數據

  //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版本時

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

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

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

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注解

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM