首页 > 解决方案 > JPA:如何读取实体的特定字段?

问题描述

我使用 Spring JPA ( Hibernate ) 并且有一堆映射到表上的实体。当我使用实体编写时,我需要其中的许多字段(请参见下面的示例)。但是当我阅读时,有时我只想阅读特定字段,例如名字/姓氏。如何使用 Spring data JPA 执行它?(因为由于CrudRepository性质,它返回整个实体)

@Entity
@Table(name="PERSON")
@AttributeOverride(name = "id", column = @Column(name = "ID_PERSON"))
public class Person extends BaseEntity implements Serializable {
     
    private static final long serialVersionUID = 1L;
     
    @Column(name="LAST_NAME", length = 100, nullable = false)
    private String lastName;
     
    @Column(name="FIRST_NAME", length = 50, nullable = false)
    private String firstName;
     
    @Column(name="MIDDLE_NAME", length = 50)
    private String middleName;
     
    @Column(name="BIRTHDAY", nullable = false)
    @Temporal(value = TemporalType.DATE)
    private Date birthday;
     
    @ManyToOne(fetch = FetchType.LAZY, optional = true)
    @JoinColumn(name = "ID_SEX")
    private Sex sex;
 
    public Person() {
        super();
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getMiddleName() {
        return middleName;
    }
    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public Sex getSex() {
        return sex;
    }
    public void setSex(Sex sex) {
        this.sex = sex;
    }  
}

标签: springhibernatejpaormspring-data-jpa

解决方案


我遇到了类似的问题,我求助于这个:

假设您的实体FooEntity与存储库相关FooRepository

假设只获取某些字段,firstName并且lastName使用key我必须在FooRepository

以这种方式

@Query("select new FooEntity(f.firstName, f.lastName) from FooEntity f where f.key = :key")
    Optional<FooEntity> findCustomByKey(@Param("key") BigInteger key);

您还必须确保FooEntity构造函数接受您只想以这种方式设置或返回的值:

  public FooEntity(String firstName, String lastName){

      // Ensure the constructor is not called with null values

       notNull(firstName, "Method called with null parameter (firstName)");
       notNull(lastName, "Method called with null parameter (lastName)");
       this.firstName = firstName;
       this.lastName = lastName;
    }

请完整代码如下:

public class FooEntity implements Serializable {

    @Id
    @Column(name = "key")
    private BigInteger key;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "birth_date")
    private Date birthDate;

    @Column(name = "hash")
    private String hash;
    
    public FooEntity(String firstName, String lastName){

      // Ensure the constructor is not called with null values

       notNull(firstName, "Method called with null parameter (firstName)");
       notNull(lastName, "Method called with null parameter (lastName)");
       this.firstName = firstName;
       this.lastName = lastName;
    }


    // Getters and Setters
    
 }

public interface FooRepository extends JpaRepository<FooEntity, BigInteger>{

    @Query("select new FooEntity(f.firstName, f.lastName) from FooEntity f where f.key = :key")
    Optional<FooEntity> findCustomById(@Param("key") BigInteger key); // This one only returns two set fields firstName and LastName and the rest as nulls

    Optional<FooEntity> findById(BigInteger key) // This one returns all the fields
}

推荐阅读