我有一份契约(Contract),其中有 2 个不同的名称但具有相同的号码,我真的只想得到一个结果,该电话号码显示在我的结果中,尽管他们的名字不同
例如,在我的数据库中,我有一个名为 name 和 phoneNumber 的列:
1. name : John, phoneNumber: 123;
2. name : Dion, phoneNumber: 123;
我真的只想得到一个只显示新的和唯一的结果,我可以通过 SELECT DISTINCT .....
来实现它,所以我只会得到唯一的,我正在尝试从联系人中选择不同的姓名、电话号码*
但是结果显示这些数据,因为它们有不同的名称,我真的结果只显示数据库中最新的数据
我有像这样的DTO(数据传输对象)
public ContactsDTO {
private String name;
private String phoneNumber;
}
我真的当我使用 JPA 获取数据时我可以将 DTO 转换为模型,它会是这样的:
[Contact(name="John", phoneNumber="123")];
我是这样使用JPA的 列表 findDistinctByPhoneNumber(); 但这是错误,
当我使用时
@Query("SELECT DISTINC new map(C.name as name, C.phoneNumber as phonenumber) from Contact C")
List<Contact> findDistnctByPhoneNumber();
结果是这样的
[{姓名:“约翰”,电话号码:“123”}]
这是该数组内对象的唯一数组,我确实喜欢你得到我喜欢的模型:
[Contact(name="John", phoneNumber="123")];
最佳答案
我想你的实体看起来像:
@Entity
@Table
public class Contact {
@GeneratedValue(strategy=GenerationType.AUTO)
@Id
private Long id;
private String name;
private String phoneNumber;
// constcutors && getters && setters
}
存储库:
public interface ContactRepository extends JpaRepository<Contact, Long> {
}
主要测试:
@SpringBootApplication
@EnableAutoConfiguration
public class ExampleH2Application {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(ExampleH2Application.class, args);
ContactRepository contactRepository = context.getBean(ContactRepository.class);
// save datas
contactRepository.saveAndFlush(new Contact("John", "123"));
contactRepository.saveAndFlush(new Contact("Dion", "123"));
contactRepository.saveAndFlush(new Contact("Albert", "548"));
List<Contact> res=new ArrayList<>();
// group by phoneNumber then select max id -> recent
Function<Contact, String> groupingComponent = Contact::getPhoneNumber;
List<Contact> list = contactRepository.findAll();
Collection<List<Contact>> collect = list.parallelStream().collect(Collectors.groupingBy(groupingComponent)).values();
collect.parallelStream().filter(Objects::nonNull).forEach(e-> res.add(Collections.max(e, Comparator.comparing(Contact::getId))));
}
}
结果如下:
[Contact [id=3, name=Albert, phoneNumber=548], Contact [id=2, name=Dion, phoneNumber=123]]
注意:在 nativeQuery 中可能有一种简单的方法可以做到这一点,但我不是这方面的专家:(
关于java - 如何从JPA中具有相同值的一列中获取sql中的唯一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56688409/