简体   繁体   English

生成JPA动态类型查询的最佳做法?

[英]Best practice to generate a JPA dynamic, typed query?

i'm trying to convert a 'TableController'-Class we used (without ORM) to generate dynamic SQL (actually the order column and direction is appended to the SQL). 我正在尝试转换我们使用的“TableController”类(没有ORM)来生成动态SQL(实际上,顺序列和方向附加到SQL)。

Think of this 'TableController' as a class that have a function to return a list of Entities of a given class (known at runtime), in a given order (String column/property name, boolean asc/desc, both at runtime). 可以将这个'TableController'看作一个类,它具有一个函数,用于以给定的顺序返回给定类的实体列表(在运行时已知)(字符串列/属性名称,布尔值asc / desc,两者都在运行时)。

The challenge is now, with JPA (Hibernate - but the customer requires to use JPA Interfaces only): How can i realize this without String concatenation, and in a type safe manner? 现在的挑战是,JPA(Hibernate - 但客户只需要使用JPA接口):如何在没有字符串连接的情况下以类型安全的方式实现这一点?

Thanks! 谢谢!

The challenge is now, with JPA (Hibernate - but the customer requires to use JPA Interfaces only): how can I realize this without String concatenation, and in a type safe manner? 现在的挑战是,JPA(Hibernate - 但客户只需要使用JPA接口):如何在没有字符串连接的情况下以类型安全的方式实现这一点?

If you're using a JPA 2.0 implementation, I think you should look at the Criteria API to build dynamic queries. 如果您正在使用JPA 2.0实现,我认为您应该查看Criteria API以构建动态查询。

If you're using JPA 1.0, there is no standard way apart from String concatenation (and my suggestion would be to use Hibernate's proprietary Criteria Queries ). 如果你正在使用JPA 1.0,除了字符串连接之外没有标准的方法(我的建议是使用Hibernate的专有Criteria Queries )。

The following article might also give you some (concrete) ideas: Hibernate Querying 102 : Criteria API . 以下文章也可能会给你一些(具体的)想法: Hibernate查询102:Criteria API


Imagine a method that has three parameters: Class entityClass, String orderByColumn, boolean ascending. 想象一个有三个参数的方法:Class entityClass,String orderByColumn,boolean ascending。 How would i create a query without string concatenation that gives me all objects of the given class in the correct order? 如何在没有字符串连接的情况下创建一个查询,以正确的顺序为我提供给定类的所有对象?

With the Criteria API from JPA 2.0, you could do something like this: 使用JPA 2.0中的Criteria API,您可以执行以下操作:

public <T> List<T> findAllEntitiesOrderedBy(Class<T> entityClass, String orderByColumn, boolean ascending) {
    CriteriaBuilder builder = em.getCriteriaBuilder();

    CriteriaQuery<T> criteria = builder.createQuery(entityClass);
    Root<T> entityRoot = criteria.from(entityClass);
    criteria.select(entityRoot);
    javax.persistence.criteria.Order order = ascending ? builder.asc(entityRoot.get(orderByColumn))
        : builder.desc(entityRoot.get(orderByColumn));
    criteria.orderBy(order);
    return em.createQuery(criteria).getResultList();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM