Spring Boot 使用Sping Boot JPARepository通过@Query从表中选择字段

eanckbw9  于 2022-11-05  发布在  Spring
关注(0)|答案(3)|浏览(170)

是否可以从表中选择一个或多个字段并将其Map到实体中?
正在尝试

@Repository
public interface RoleRepo extends JpaRepository<Role, Long>{  
    @Query("SELECT r.roleId, r.name FROM role r")  
    List<Role> getAllRoleNames();
}

我只需要这两个值,其余的字段可以是null,这样效率更高。

ConversionFailedException: Failed to convert from type [java.lang.Object[]] to type 
[@org.springframework.data.jpa.repository.Query demo.model.Role] for value '{1, Java Dev}'; 
nested exception is org.springframework.core.convert.ConverterNotFoundException: 
No converter found capable of converting from type [java.lang.Long] to type 
[@org.springframework.data.jpa.repository.Query demo.model.Role]] with root cause

那么,当我不能只说object.Id = role.roleIdobject.Id就是1)时,我如何才能进行转换呢?

dtcbnfnu

dtcbnfnu1#

通过Spring Data,您可以使用投影来完成此操作。

@Entity
public class ExampleEntity {

    @Id
    private Long id;

    @OneToOne
    private Person person;

    private String name;

    // getters and setters
}

public interface ExampleProjection {
    String getName(); // This must be exactly the same as your entity
}

现在,您可以在存储库中使用ExampleProjection,即使存储库引用ExampleEntity而不是Projection。

public interface ExampleRepository extends Repository<ExampleEntity, Long> {
    List<ExampleProjection> findBy();
}

更多信息,请访问:https://www.baeldung.com/spring-data-jpa-projections

fzwojiic

fzwojiic2#

在Spring中,您可以使用自定义实体,如下所示:
NewRole.java

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class NewRole implements Serializable {

private static final long serialVersionUID = 1L;
@Id
private Long id;
private String name;

}

RoleRepo.java

@Repository
public interface RoleRepo extends JpaRepository<Role, Long> {  

@Query("SELECT new NewRole(r.id, r.name) FROM role r")  
List<NewRole> getAllRoleNames();

}

祝你好运!

vnzz0bqm

vnzz0bqm3#

我只是通过添加一个新的构造函数来修改查询,以便填充我需要的字段,而其他字段为空。

@Repository
public interface RoleRepo extends JpaRepository<Role, Long>{  
    @Query("SELECT new demo.model.Role(r.roleId, r.name) FROM role r")  
    List<Role> getAllRoleNames();
}

@AllArgsConstructor //all arg constructor
@Data
@Entity(name = "role")
public class Role {
    public Role(Long roleId, String name) { //half arg constructor
        this.roleId = roleId;
        this.name = name;
    }

    @Id
    private Long roleId;

    private String name;

    // more fields, getters, and setters
}

相关问题