Automatic trimming in QueryDSL with Bean Projection

末鹿安然 提交于 2019-12-13 15:27:12

问题


I have the following QueryDSL query:

List<DTOPerson> names = query.from(p)
  .where(p.lastname.like("%smith%"))
  .orderBy(p.lastname.asc(), p.firstname.asc())
  .list(Projections.bean(DTOPerson.class, p.lastname, p.firstname));

What I would like to have is this:

List<DTOPerson> names = query.from(p)
  .where(p.lastname.like("%smith%"))
  .orderBy(p.lastname.asc(), p.firstname.asc())
  .list(Projections.bean(DTOPerson.class, p.lastname.trim(), p.firstname.trim()));

But when I do that, QueryDSL gives me this error:

java.lang.IllegalArgumentException: Unsupported expression trim(p.lastname)
  at com.mysema.query.types.QBean.createBindings(QBean.java:59)
  at com.mysema.query.types.QBean.<init>(QBean.java:149)
  at com.mysema.query.types.QBean.<init>(QBean.java:138)
  at com.mysema.query.types.Projections.bean(Projections.java:51)    

Is there a way to trim (all) string results?


回答1:


You will need to use explicit aliases in this case, because Querydsl accepts only paths and alias-operations as arguments to QBean.

List<DTOPerson> names = query.from(p)
  .where(p.lastname.like("%smith%"))
  .orderBy(p.lastname.asc(), p.firstname.asc())
  .list(Projections.bean(DTOPerson.class, 
      p.lastname.trim().as("lastname"), 
      p.firstname.trim().as("firstname")));

Is there a way to trim (all) string results?

You can create a custom FactoryExpression, e.g. subclass of QBean, to do that.



来源:https://stackoverflow.com/questions/22092002/automatic-trimming-in-querydsl-with-bean-projection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!