Spring Data JPA 使用Specification 实现动态查询分析

java哥 阅读:268 2021-03-31 13:19:10 评论:0

实体对象

package com.zzg.entity; 
 
 
 
import java.util.Date; 
 
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 
 
import lombok.Getter; 
import lombok.Setter; 
 
@Getter 
@Setter 
@Entity 
public class User { 
	@Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增长策略 
	private Integer useId; 
	 
	@Column 
	private String useName; 
	 
	@Column 
	private String useSex; 
	 
	@Column 
	private Integer useAge; 
	 
	@Column 
	private String useIdNo; 
	 
	@Column 
	private String usePhoneNum; 
	 
	@Column 
	private String useEmail; 
	 
	@Column 
	private Date createTime; 
	 
	@Column 
	private Date modifyTime; 
	 
	@Column 
	private String useState; 
} 

Dao层定义

package com.zzg.dao; 
 
import org.springframework.data.jpa.repository.JpaRepository; 
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 
import org.springframework.stereotype.Repository; 
 
import com.zzg.entity.User; 
 
@Repository 
public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> { 
 
} 

Controller层定义:使用Specification 实现动态查询

package com.zzg.controller; 
 
import java.util.ArrayList; 
import java.util.List; 
 
import javax.persistence.criteria.CriteriaBuilder; 
import javax.persistence.criteria.CriteriaQuery; 
import javax.persistence.criteria.Predicate; 
import javax.persistence.criteria.Root; 
 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.data.jpa.domain.Specification; 
import org.springframework.web.bind.annotation.GetMapping; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RestController; 
 
import com.zzg.dao.UserRepository; 
import com.zzg.entity.User; 
 
@RestController 
public class UserController { 
	@Autowired 
	private UserRepository userRepository; 
	 
	 
	@GetMapping("/user/{id}") 
    public User findById(@PathVariable Integer id) { 
        return userRepository.findOne(new Specification<User>() { 
			 
			@Override 
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { 
				// TODO Auto-generated method stub 
				 List<Predicate> predicates = new ArrayList<Predicate>(); 
	             // 用户编号 
	             predicates.add(criteriaBuilder.equal(root.<Integer> get("useId"), id)); 
	                 
				return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction(); 
			} 
		}).orElse(null); 
    } 
 
} 

 

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
KIKK导航

KIKK导航

排行榜
关注我们

一个IT知识分享的公众号