我使用Spring JPA执行所有数据库操作。但是,我不知道如何从Spring JPA的表中选择特定的列?

例如: SELECT projectName FROM projects


当前回答

您可以使用来自Spring Data JPA(文档)的投影。在你的例子中,创建接口:

interface ProjectIdAndName{
    String getId();
    String getName();
}

并将以下方法添加到存储库中

List<ProjectIdAndName> findAll();

其他回答

你可以更新你的JPARepository,如下所示。

@Query("select u.status from UserLogin u where u.userId = ?1 or u.email = ?1 or u.mobile = ?1")
public UserStatus findByUserIdOrEmailOrMobile(String loginId);

UserStatus为Enum

public enum UserStatus
{
    New,
    Active,
    Deactived,
    Suspended,
    Locked
}

在我看来,这是一个很好的解决方案:

interface PersonRepository extends Repository<Person, UUID> {

    <T> Collection<T> findByLastname(String lastname, Class<T> type);
}

像这样使用它

void someMethod(PersonRepository people) {

  Collection<Person> aggregates =
    people.findByLastname("Matthews", Person.class);

  Collection<NamesOnly> aggregates =
    people.findByLastname("Matthews", NamesOnly.class);
}

你可以使用@jombie给出的答案,并且:

将接口放在实体类之外的单独文件中; 是否使用本机查询(选择取决于您的需要); 不要为此重写findAll()方法,而是使用自己选择的名称; 记得用你的新接口返回一个参数化的List(例如List<SmallProject>)。

在我的情况下,我创建了一个单独的实体类,没有字段是不需要的(只有字段是必需的)。

将实体映射到同一个表。 现在当所有的列都是必需的,我使用旧的实体,当只有一些列是必需的,我使用lite实体。

如。

@Entity
@Table(name = "user")
Class User{
         @Column(name = "id", unique=true, nullable=false)
         int id;
         @Column(name = "name", nullable=false)
         String name;
         @Column(name = "address", nullable=false)
         Address address;
}

你可以创建如下内容:

@Entity
@Table(name = "user")
Class UserLite{
         @Column(name = "id", unique=true, nullable=false)
         int id;
         @Column(name = "name", nullable=false)
         String name;
}

当您知道要获取的列时,这是有效的(这不会改变)。

如果你需要动态地决定列,这是行不通的。

使用Spring Data JPA有一个从数据库中选择特定列的规定

----在DAOImpl ----

@Override
    @Transactional
    public List<Employee> getAllEmployee() throws Exception {
    LOGGER.info("Inside getAllEmployee");
    List<Employee> empList = empRepo.getNameAndCityOnly();
    return empList;
    }

----在回购----

public interface EmployeeRepository extends CrudRepository<Employee,Integer> {
    @Query("select e.name, e.city from Employee e" )
    List<Employee> getNameAndCityOnly();
}

这对我来说是100%有效的。 谢谢。