我正在尝试从其他查询中选择信息,例如:
SELECT user.user_id, product.first_time
FROM USER AS user
INNER JOIN (SELECT min(product.first_time) as first_time,
product.user_id
FROM PRODUCT AS product
GROUP BY (product.user_id)
) product
ON user.user_id = product.user_id
但我不知道如何创建一个Criteria Query来执行它。 我可以使用Criteria API执行它吗?
答案 0 :(得分:0)
尝试使用此: https://docs.jboss.org/hibernate/orm/4.3/topical/html/metamodelgen/MetamodelGenerator.html
需要创建元类你的实体。
示例,您的服务类:
@Service("jpaCustomerService")
@Repository
@Transactional
public class CustomerServiceImpl implements CustomerService {
@PersistenceContext
private EntityManager em;
@Transactional(readOnly = true)
public List<CustomersEntity> findByCriteriaQuery(String name){
CriteriaBuilder cb = em.getCriteriaBuilder();
javax.persistence.criteria.CriteriaQuery<CustomersEntity> criteriaQuery = cb.createQuery(CustomersEntity.class);
Root<CustomersEntity> customersEntityRoot = criteriaQuery.from(CustomersEntity.class);
customersEntityRoot.fetch(CustomersEntity_.animal, JoinType.LEFT);
criteriaQuery.select(customersEntityRoot).distinct(true);
Predicate criteria = cb.conjunction();
if (!name.isEmpty()){
Predicate p = cb.equal(customersEntityRoot.get(CustomersEntity_.name), name);
criteria = cb.and(criteria, p);
}
criteriaQuery.where(criteria);
List<CustomersEntity> result = em.createQuery(criteriaQuery).getResultList();
return result;
}
}
和你的控制者或你的主人:
public static void criteriaExample(GenericXmlApplicationContext ctx){
CustomerService service = ctx.getBean("jpaCustomerService", CustomerService.class);
List<CustomersEntity> creteriaResult = service.findByCriteriaQuery("NCI-3");
for (CustomersEntity customer : creteriaResult){
System.out.println(customer);
if (!customer.getAnimal().isEmpty())
for (AnimalsEntity animal : customer.getAnimal()){
System.out.println(animal);
}
}
}
CustomersEntity_ - 元模型类。不需要SQL查询。
你的infs是:
public interface CustomerService {
List<CustomersEntity> findByCriteriaQuery(String name);}