Gon*_*oso 6 java database querydsl
我正在尝试使用QueryDSL从我的表中获取多列的列表,并自动填充我的数据库对象,如旧手册中的此示例:
List<CatDTO> catDTOs = query.from(cat)
.list(EConstructor.create(CatDTO.class, cat.id, cat.name));
Run Code Online (Sandbox Code Playgroud)
问题是看起来在版本2.2.0中删除了EConstructor类,我现在找到的所有示例都是这样的:
List<Object[]> rows = query.from(cat)
.list(cat.id, cat.name);
Run Code Online (Sandbox Code Playgroud)
这迫使我手动将所有对象强制转换为我的CatDTO类.
有没有替代方案?任何EConstructor替代?
EConstructor已被Querydsl 2.0中的ConstructorExpression取代.所以你的榜样就会变成
List<CatDTO> catDTOs = query.from(cat)
.list(ConstructorExpression.create(CatDTO.class, cat.id, cat.name));
Run Code Online (Sandbox Code Playgroud)
您还可以注释CatDTO构造函数并像这样查询
List<CatDTO> catDTOs = query.from(cat)
.list(new QCatDTO(cat.id, cat.name));
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用QTuple投影,它提供更通用的访问选项
List<Tuple> rows = query.from(cat)
.list(new QTuple(cat.id, cat.name));
Run Code Online (Sandbox Code Playgroud)
可以通过这样的路径访问实际值
tuple.get(cat.id)
Run Code Online (Sandbox Code Playgroud)
和
tuple.get(cat.name)
Run Code Online (Sandbox Code Playgroud)
元组投影可能会在Querydsl 3.0中用于多列投影而不是Object数组.
使用 queryDSL 4 和 Java 8 流:
List<CatDTO> cats = new JPAQueryFactory(entityManager)
.select(cat.id, cat.name)
.from(cat)
.fetch()
.stream()
.map(c -> new CatDTO(c.get(cat.id), c.get(cat.name)))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10495 次 |
| 最近记录: |