Springboot JPA使用distinct返回对象

package com.frank.jpaBatchSave.repository;

import com.frank.jpaBatchSave.entity.Person;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PersonRepository extends PagingAndSortingRepository<Person, Integer> {

//    https://blog.csdn.net/zccbbg/article/details/84170868
    @Query("select distinct new Person(p.name, p.province, p.city) from Person p")
    List<Person> getAllPerson();
}

这里如果需要返回的是对象,则需要new Person(p.name, p.province, p.city),同时Person类必须要有三参的构造器。

public Person(String name, String province, String city) {
        this.name = name;
        this.province = province;
        this.city = city;
    }

因为:select distinct name, province, city) from Person p 这样写的话返回的是Object[]数组。所以需要使用上面的方式。

猜你喜欢

转载自blog.csdn.net/qq_33371766/article/details/110331817