(原)SpringBoot JPA 单表/多表联合查询 [ 不用一对多等方式 hibernate 元数据 ]

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31653405/article/details/82876060

一、SpringBoot   JPA 单表 联合查询

                          Spring Data JPA虽然大大的简化了持久层的开发,但是在实际开发中,很多地方都需要高级动态查询,在实现动态查询时我们需要用到Criteria API,主要是以下三个:

  1、Criteria 查询是以元模型的概念为基础的,元模型是为具体持久化单元的受管实体定义的,这些实体可以是实体类,嵌入类或者映射的父类。

  2、CriteriaQuery接口:代表一个specific的顶层查询对象,它包含着查询的各个部分,比如:select 、from、where、group by、order by等注意:CriteriaQuery对象只对实体类型或嵌入式类型的Criteria查询起作用

  3、Root接口:代表Criteria查询的根对象,Criteria查询的查询根定义了实体类型,能为将来导航获得想要的结果,它与SQL查询中的FROM子句类似

 /**
 1.调用entityManager.getCriteriaBuilder()来获取CriteriaBuilder。CriteriaBuilder可以用于创建CriteriaQuery、CriteriaUpdate和CriteriaDelete。除此之外类似count、max等函数也是由CriteriaBuilder来创建的。其中Entitymanager可以使用@PersistenceContext注解来进行注入。
 2.调用criteriaBuilder.createQuery来创建CriteriaQuery。其中createQuery的参数是Query返回值类型。
 3.调用query.from(Order.class)。参数是对应于order表的实体类,query.from类似于sql中的from语句,该方法的执行等价于sql中的from order。
 4.调用 query.select创建映射。 query.select(criteriaBuilder.count(root.get(“id”)))等价于select count(id)。如果执行query.select(root)则等价于select *。
 5.使用CriteriaBuilder构造查询条件Predicate,该predicate也就是在where后面的条件子句。
 6.将Predicate放在 query.where中。
 7.最后执行查询获取数据。
  
   **/ 
	 CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
     CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class);
     Root<Order> root = query.from(Order.class);
     query.select(criteriaBuilder.count(root.get("id")));
     Predicate predicate = criteriaBuilder.equal(root.get("id"), 1);
     query.where(predicate);
     Long singleResult = entityManager.createQuery(query).getSingleResult();

1、创建model:

2、编写serviceimplement接口:

	@Autowired 
    EntityManager entityManager;


public List<Product> getPruductList(final String maxType, final String selectVal,final String productTypeVal, final String productPricesVal) {
		    //基础sql
		    String sql = "FROM Product  WHERE 1 = 1  AND  product_style = '" +maxType+"' ";
		    List<Predicate> predicates = new ArrayList<Predicate>();
		    
		    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
	        CriteriaQuery<Product> query = cb.createQuery(Product.class);
	        Root<Product> root = query.from(Product.class);
	         //where
	        Predicate Predicate1 = null;
			
			if( productTypeVal != null ) {
				Predicate Predicate2 = null;
				List<String> list = Arrays.asList("1","2","3","4","5","6");
				if(list.contains(productTypeVal) == true) {
					sql+= "  AND  product_style_detailed = '"+productTypeVal+"' ";
					Predicate2 =  cb.equal(root.get("productStyleDetailed"), productTypeVal);
				}
				if (Predicate2 != null) {
					Predicate1 = cb.and(Predicate1, Predicate2);
	            } else {
	            	Predicate1 = Predicate2;
	            }
				predicates.add(Predicate1);
				query.where(predicates.toArray(new Predicate[predicates.size()]));
				
			}
			if(productPricesVal!= null) {
				Predicate Predicate2 = null;
				System.out.println(productPricesVal);
				if(productPricesVal.equals("1")) {
					sql += " AND favorable_price between 0 and 999.99 ";
					Predicate2=  cb.equal(root.get("favorablePrice"), productPricesVal);
				}
				if(productPricesVal.equals("2")) {
					sql += " AND favorable_price between 1000 and 1999.99 ";
					Predicate2=  cb.equal(root.get("favorablePrice"), productPricesVal);
				}
				if(productPricesVal.equals("3")) {
					sql += " AND favorable_price >= 2000 ";
					Predicate2=  cb.equal(root.get("favorablePrice"), productPricesVal);
				}
				if (Predicate2 != null) {
					Predicate1 = cb.and(Predicate1, Predicate2);
	            } else {
	            	Predicate1 = Predicate2;
	            }
				predicates.add(Predicate1);
				query.where(predicates.toArray(new Predicate[predicates.size()]));
			}
			
			   if(selectVal!= null && !"0".equals(selectVal)) {
		        	Predicate Predicate2 = null;
					System.out.println(selectVal);
					if(selectVal.equals("2")) {
						sql += " ORDER BY product_name ASC";
					    Predicate2 =  cb.equal(root.get("productName"), selectVal);
					}
					if(selectVal.equals("3")) {
						sql += " ORDER BY product_price ASC";
						Predicate2 =  cb.equal(root.get("productPrice"), selectVal);
					}
					if(selectVal.equals("4")) {
						sql += " ORDER BY product_price DESC";
						Predicate2 =  cb.equal(root.get("productPrice"), selectVal);
					}
					
					if (Predicate2 != null) {
						Predicate1 = cb.and(Predicate1, Predicate2);
		            } else {
		            	Predicate1 = Predicate2;
		            }
					predicates.add(Predicate1);
					query.where(predicates.toArray(new Predicate[predicates.size()]));
				}
			   
			System.out.println(sql);
			
			List<Product> productlist = entityManager.createQuery(sql).getResultList();
			System.out.println("size-------"+ productlist.size());
			
			return productlist;
	}

3、程序运行:(形如以下结构)

Hibernate: select 
               product0_.product_id as product_1_16_,

               product0_.product_name as product11_16_
 
             from drp_product product0_
            
             where 1=1 
                and product_style='0' 
                and product_style_detailed='1' 
                and (favorable_price between 0 and 999.99) 
           
             order by product_name ASC

                                                                                                                                                     程序可以直接用,经过测试!!!


二、SpringBoot   JPA 多表联合查询

【 后期 做 】

----------------------------------------------------------------------------------------------------------------

文章中,有问题,可以在评论区评论,一起探讨编程中奥秘!

----------------------------------------------------------------------------------------------------------------

来都来了,代码看都看了,那就留个言呗,可以互动下!

----------------------------------------------------------------------------------------------------------------

转载声明:本文为博主原创文章,未经博主允许不得转载。

猜你喜欢

转载自blog.csdn.net/qq_31653405/article/details/82876060