Spring Data JPA用于返回特定字段

14

Spring Data是否有返回特定字段的机制?

我熟悉如下语法:

Invoice findByCode(String code);

这个怎么样:

Integer findIdByCode(String code);

仅返回id字段的方法。或者

Tuple findIdAndNameByCode(String code);

返回一个元组。或者

Invoice findIdAndNameByCode(String code);

该方法返回仅填充了特定字段的实体。如果定义了只使用这些字段的构造函数,则可以使用该构造函数,否则构造一个空实体并填充这些字段。

编辑

更进一步地说,我知道像@Query、构造函数表达式和现在的@NamedEntityGraph这样的解决方案。我的问题很简单 - Spring Data是否支持我所建议的这种简写语法?

如果不支持,也许这是以后版本的一个很酷的增强功能...

我不想要变通方法。


参见参考指南需要JPA 2.1和最新的Spring Data JPA版本。 - M. Deinum
NamedEntityGraph是一个有用的功能,但比使用@Query更冗长来解决我的情况。我希望看到一种没有任何注释的解决方案。 - Gilbert
@Query 不是一个注解,你想绕过默认的解决方案。无论如何,你都需要做一些事情来返回你想要的数据子集,使用默认的方式可以在进行查询时重复使用,而不必每次都创建许多不同的构造函数。 - M. Deinum
作为附注,我正在使用Hibernate,并且它不限制返回的字段:https://hibernate.atlassian.net/browse/HHH-9270 - Gilbert
2
不,没有这方面的速记方式,那只能适用于特定的查询或规范。 - M. Deinum
4个回答

4

您可以使用JPQL构造函数表达式

SELECT NEW com.company.PublisherInfo(pub.id, pub.revenue, mag.price)
    FROM Publisher pub JOIN pub.magazines mag WHERE mag.price > 5.00

构造函数的名称必须是完全限定的。

现在也可以查看投影了,虽然不完全是您想要的,但更接近 - http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections - chrismarx

1
如果你想从表中只返回一个基本类型(或自动装箱)字段,可以使用以下代码:
@Query("select distinct t.locationId from Table t")
List<Long> findAllWashroomLocationId();

在哪里:

  • Table - 表示您的表的类名
  • t - 别名
  • locationId - 字段名称(在您的Table对象中)
  • Long - locationId的类型(整数,字符串等)

1

不确定你所尝试实现的是否与在同一JPA生成的查询上使用多个投影相同(其中方法名称相同)。

我在此帖子中发布了答案。

https://dev59.com/GaDia4cB1Zd3GeqPJtLu#43373337

So I've managed to figure out how to use multiple projections with a single query.

<T> T getByUsername(String username, Class<T> projection) This allows the method caller to specified the type of projection to be

applied to the query.

To further improve this so it is less prone to error, I made a blank interface that the projection will have to extend in order to be able to insert class into the parameter.

public interface JPAProjection {
}

public interface UserRepository extends CrudRepository<UserAccount, Long> {
    <T extends JPAProjection > T getByUsername(String username, Class<? extends JPAProjection> projection);
}

Projection Interface

public interface UserDetailsProjection extends JPAProjection{
    @Value("#{target.username}")
    String getUsername();

    @Value("#{target.firstname}")
    String getFirstname();

    @Value("#{target.lastname}")
    String getLastname();
}

Then I can call the query method by

getByUsername("...", UserDetailsProjection.class)

0
我有一个NativeQuery, 这是一个插入操作,我将使用"RETURNING *"返回插入后的所有字段。
此查询将返回我的数据库中的所有字段,并将保存在我的实体“Perfil Detalles”中。 我的实体具有我数据库字段的所有配置。
@Query(
        value= "INSERT INTO \"USUARIO\".\"PERFIL_CONFIGURACION\" (id_perfil, id_group, id_role) VALUES(:id_perfil, :id_group, :id_role) returning *",
        nativeQuery = true)
        public PerfilDetalles insertPerfilDetalles(
        @Param("id_perfil") Long id_perfil,
        @Param("id_group") int id_group,
        @Param("id_role") int id_role); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接