JPA2.0学习笔记---Criteria 查询

@Override
	public List<Book> getBookByTitle(String title) {

		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Book> c = cb.createQuery(Book.class);
		
		Root<Book> book = c.from(Book.class);
		c.select(book);    //类似于  from Book b  这个里面的b
		c.distinct(true);  // 去除重复行
		//构建参数
		List<Predicate> criteList = new ArrayList<Predicate>();
		if (title != null) {
			ParameterExpression<String> p = cb.parameter(String.class, "title");
			//criteList.add(cb.equal(book.get("title"), p));
			
			cb.and(cb.equal(book.get("title"), p));
		}
		

		if (criteList.size() == 0) {
			throw new RuntimeException("no criteria");
		} else if (criteList.size() == 1) {
			c.where(criteList.get(0));
		} else {
			c.where(cb.and(criteList.toArray(new Predicate[0])));
		}
		
		TypedQuery<Book> q = em.createQuery(c);
		if(title != null) q.setParameter("title", title);
		return q.getResultList();
	}



下面是简化版~  适合一个

@Override
	public List<Book> getBookByTitle(String title) {

		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Book> c = cb.createQuery(Book.class);
		
		Root<Book> book = c.from(Book.class);
		c.select(book);
		ParameterExpression<String> pe_title = cb.parameter(String.class,"title");
		
		c.where(cb.equal(book.get("title"), pe_title));
		
		
		TypedQuery<Book> q = em.createQuery(c);
		if(title != null) q.setParameter("title", title);
		return q.getResultList();
	}


你可能感兴趣的:(c,String,jpa,null)