【问题标题】:spring data, PagingAndSorting repository, Sort based on (nested) attribute value of class typespring data, PagingAndSorting repository, Sort based on (nested) attribute value of class type
【发布时间】:2020-04-06 10:29:31
【问题描述】:

我有一个由 Persons 组成的简单应用程序的 PagingAndSorting 存储库。 像年龄这样的属性的简单排序效果很好......

Sort sort = Sort.by("age").ascending();

for (Person p : personRepository.findAll(sort)) {
    log.info(p.toString());
}

我也想按姓氏对人员进行排序。但我没有为名字和姓氏创建两个属性。我创建了一个包含名字和姓氏的类 Name 并在 Person 中创建了这种类型的 name 属性...

@Entity
public class Person {
    // ...  
@Convert(converter = NameAttributeConverter.class)
@Column

private Name name;
    // ...
}

public final class Name implements Comparable, Serializable {
      // ...
      private String firstName;
      private String lastName;
      // ...
}

public class NameAttributeConverter implements AttributeConverter<Name,String> {
 {
        String firstName = attribute.getFirstName() == null ? " " : attribute.getFirstName();
        String lastName =  attribute.getLastname() == null ? " " : attribute.getLastname();

        return  firstName+" "+lastName;
    }

    public Name convertToEntityAttribute(String dbData) {
        if(dbData!=null && dbData.split(" ").length > 0) {
            String fname = dbData.split(" ")[0];
            String lname = dbData.split(" ")[1];

            return new Name(fname,' ',lname);
          }

          return null;
    }
}

如何按姓(或名字)排序?类似的东西

Sort sort = Sort.by("name").ascending();

for (Person p : personRepository.findAll(sort)) {
    log.info(p.toString());
}

执行并且没有错误(例如,人被打印在控制台上)但没有像预期的那样工作。

它使用名字升序排序(不知道为什么)。

如何根据类名的 lastName 属性进行排序?

感谢和问候

【问题讨论】:

标签: java spring-boot sorting jpa spring-data-jpa


【解决方案1】:

您将name 列的数据作为firstName+" "+lastName 存储在数据库中。

所以 JPA 按名称排序数据意味着按firstName+" "+lastName 排序。

如果您在数据库单独的列中定义名字和姓氏,则也可以按姓氏排序。 你可以按照我的回答here来解决这个问题。

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 2022-12-19
    • 2022-12-02
    • 2022-12-02
    • 2020-12-24
    • 2014-11-14
    • 2013-05-26
    • 2020-06-12
    • 1970-01-01
    相关资源
    最近更新 更多