自最初任职4年以来,有一些发展。使用 spring 4 和 Hibernate 4,现在可以使用 SpEL 表达式“欺骗”Hibernate。例如:
枚举:
package com.mycompany.enums
public enum Status {
INITIAL, PENDING, REJECTED, APPROVED, SHIPPED, DELIVERED, COMPLETE;
}
下面是一个名为“Filter”的包装类,我们将将其传递给存储库筛选方法。
package com.mycompany.enums
public class Filter implements Serializable {
/** The id of the filtered item */
private Integer id;
/** The status of the filtered item */
private Status status;
// more filter criteria here...
// getters, setters, equals(), hashCode() - omitted for brevity
/**
* Returns the name of the status constant or null if the status is null. This is used in the repositories to filter
* queries by the status using a the SPEL (T) expression, taking advantage of the status qualified name. For example:
* {@code :#{T(com.mycompany.enums.Status).#filter.statusName}}
*
* @return the status constant name or null if the status is null
*/
public String getStatusName() {
return null == status ? status : status.name();
}
}
最后,在存储库中,我们现在可以将 Filter 类用作单个参数,并使查询将看似文本和 SpEL 表达式的混合内容转换为 Status 对象:
存储库:
package com.mycompany.repository
@Repository
public interface OrderRepository extends CrudRepository<Order, Integer> {
@Query("SELECT o from Order o "
+ "WHERE o.id = COALESCE(:#{#filter.id},o.id) "
+ "AND o.status = COALESCE(:#{T(com.mycompany.enums.Status).#filter.statusName},o.status)")
public List<Order> getFilteredOrders(@Param(value = "filter") Filter filter);
}
这很完美,但是由于一些奇怪的原因,我还没有弄清楚,如果你在Hibernate中启用SQL调试并打开绑定器日志记录,你将无法看到Hibernate将此表达式绑定到查询变量。