我遇到了一个问题。
我搜索了几个小时,但没找到任何一个。
我想要做的是一个sql select,其中ORDER子句取决于列的值(因此它会针对每个元组进行更改)。
我设法通过HQL做到这一点:
SELECT NEW myDTO(m.id, m.name, " + calculDistance + " AS distance) FROM Table m GROUP BY m.mercId ORDER BY distance ASC
calculDistance取决于m.latitude和m.longitude
这很好用。 但是,我的要求比这要复杂得多,而且对于阅读,更新等原因,我想直接用JPA来做。
你知道这是否可能吗?
感谢您的帮助。
修改
这是我的表结构的一部分(我只放了所需的列):
@Entity
@Table(name = "td_merchant")
@XmlRootElement
@SequenceGenerator(name = "td_merchant_id_seq", sequenceName = "td_merchant_id_seq")
public class Merchant implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "td_merchant_id_seq", strategy = GenerationType.SEQUENCE)
@Column(name = "merc_id")
private Integer mercId;
@Column(name = "merc_name")
private String mercName;
@Column(name = "merc_latitude")
private Double mercLatitude;
@Column(name = "merc_longitude")
private Double mercLongitude;
...
}
答案 0 :(得分:0)
I also faced same issue, i wrote one function which was taking input for order by as well as asc and desc seq.
public List<CompanyName> loadAllCompanies(CompanySortField sortField, boolean ascending) {
String queryString = "select new com.Company(u.name, u.surname, " +
" country.name, country.population, " +
" city.name) from Company u left join u.city as city left join u.country as country " +
" order by " + sortField.getField() + (ascending ? " asc " : " desc ");
return entityManager.createQuery(queryString).getResultList();
}
您可以尝试这种方式,只需要触发另一个查询来查找公司排序字段。