JPA 2.0 학습 노트 --- Criteria 조회

1686 단어 cStringjpanull
@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();
	}

좋은 웹페이지 즐겨찾기