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

 

猜你喜欢

转载自www.cnblogs.com/fdzang/p/9560054.html