Skip to content

Instantly share code, notes, and snippets.

@darbyluv2code
Created June 29, 2017 14:53
Show Gist options
  • Select an option

  • Save darbyluv2code/3fe2a699ea7ec9e0621f3d7ca180dd35 to your computer and use it in GitHub Desktop.

Select an option

Save darbyluv2code/3fe2a699ea7ec9e0621f3d7ca180dd35 to your computer and use it in GitHub Desktop.
Milos - Updates for new Criteria API
package com.juratech.springdemo.dao;
import java.util.List;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.juratech.springdemo.entity.Customer;
@Repository
public class CustomerDAOImpl implements CustomerDAO {
//need to inject the session factory
@Autowired
private SessionFactory sessionFactory;
@Override
public List<Customer> getCustomers() {
return getCustomersBy("firstName");
}
@Override
public void saveCustomer(Customer theCustomer) {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
//save the customer ... finally
currentSession.save(theCustomer);
}
public List<Customer> getCustomersBy(String theSortField) {
Session currentSession = sessionFactory.getCurrentSession();
//
// Using new Criteria Query API
// - docs: https://docs.oracle.com/javaee/7/tutorial/persistence-criteria.htm#GJITV
//
//
// Create CriteriaBuilder
CriteriaBuilder builder = currentSession.getCriteriaBuilder();
// Create CriteriaQuery
CriteriaQuery<Customer> theCriteria = builder.createQuery(Customer.class);
// For a particular CriteriaQuery object, the root entity of the query,
// from which all navigation originates, is called the query root.
// It is similar to the FROM clause in a JPQL query.
//
Root<Customer> customer = theCriteria.from(Customer.class);
theCriteria.select(customer);
theCriteria.orderBy(builder.asc(customer.get(theSortField)));
// create query based on criteria
TypedQuery<Customer> query = currentSession.createQuery(theCriteria);
// execute the query
List<Customer> customers = query.getResultList();
return customers;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment