如何根据 @ManyToMany 关系的 Id 对 Set 进行排序?

How to sort a Set by its Id of a @ManyToMany relation?

我想在我正在开发的 Web 应用程序中按 @ManyToMany 关系的 ID 对集合进行排序,但我不知道该怎么做。目前 Set 以创建 ManyToMany 关系的顺序显示。

Class特别

@Entity
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public class Especie extends Familia{

    @GeneratedValue
    private Integer diasGerminacionDesde;
    private Integer diasGerminacionHasta;

    @ManyToOne
    private Familia familia;

    @JoinTable(
        name = "especie_mesesSiembra"
        ,joinColumns=@JoinColumn(name="especie_id")
        ,inverseJoinColumns=@JoinColumn(name="mesSiembra_id")
    )

    @ManyToMany
    private Set<MesSiembra> mesesSiembra;
}

Class EspecieControlador(控制器)

@GetMapping
public List<Especie> listarTodos() {
    return servicio.listarTodos();
}

Class EspecieServicio(服务)

public List<Especie> listarTodos() {
    Sort orden = Sort.by(Sort.Direction.ASC, "nombre");
    return repositorio.findAll(orden);
}

您可以使用 LinkedHashSet + JPA 注释 @OrderBy

@OrderBy
private Set<MesSiembra> mesesSiembra = new LinkedHashSet<>();

我已经替换了这个:

@ManyToMany
private Set<MesSiembra> mesesSiembra;

为此:

@OrderBy("mesSiembra_id")
private Set<MesSiembra> mesesSiembra = new LinkedHashSet<>();

在 Spring 引导控制台中,我收到以下错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'especieRepositorio' defined in ar.com.mibancosemillas.bancosemillasweb.persistencia.EspecieRepositorio defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: familia, for columns: [org.hibernate.mapping.Column(meses_siembra)]