SpringData JPA动态投影从MySQL中检索所有列



我有一个表示MySQL表的实体:

@Entity
@Table(name = "account")
@Getter
@Setter
@SuppressWarnings("serial")
public class AccountEntity implements AccountBaseEntity, AccountRoleEntity, Serializable {
@Id
@GeneratedValue(generator = "uuid2")
@Column(name = "account_id")
private UUID accountId;
@Column(name = "email")
@NotBlank
private String email;
@Column(name = "role")
@NotBlank
private String role;
@Column(name = "creation_time")
@NotNull
private Timestamp creationTime;
}

它实现了这个接口:

public interface AccountBaseEntity {
UUID getAccountId();
}

然后我有一些预测也在实现它。例如:

public interface AccountRoleEntity extends AccountBaseEntity {
String getRole();
}

这是我的存储库,它有一个动态投影:

public interface AccountsRepository extends JpaRepository<AccountEntity, UUID> {
<T extends AccountBaseEntity> T findByEmail(String email, Class<T> type);
}

我把它和这个代码一起使用:

AccountRoleEntity accountRoleEntity = accountsRepository.findByEmail(email, AccountRoleEntity.class);

我检查了设置Spring Boot属性spring.jpa.show-sql = true的查询,这就是我所看到的:

Hibernate: select accountent0_.account_id as account_1_0_, accountent0_.creation_time as creation2_0_, accountent0_.email as email3_0_, accountent0_.role as role10_0_ from account accountent0_ where accountent0_.email=?

我希望查询只选择account_id和role列,但它似乎是在检索实体并将其转换为投影,而不是检索投影本身。这是bug还是我做错了什么?

我刚刚意识到这是因为AccountEntity扩展了AccountRoleEntity。这是正常行为吗?

我希望实体扩展投影,这样我就可以在一些应该同时使用实体和投影的方法中使用一个公共接口。

编辑:

如本文所述(https://github.com/spring-projects/spring-data-jpa/issues/2179),这是预期的行为。这就解决了创建一个由实体和投影实现的超级接口的问题。

最新更新