如何在休眠中的@ManyToMany 关系中对 mapping/third table 的 ID 使用 orderby

How to use orderby on ID of mapping/third table in @ManyToMany relation in hibernate

我有两个主要 table 和一个映射 table 用于多对多关系。我想在 PACKAGE_ACTION_MAPPING table Id 列上应用 @OrderBy("ID ASC")。但是,当我使用@OrderBy("ID ASC") 时,排序应用于 Int_Action Id 列而不是 PACKAGE_ACTION_MAPPING Id 列。

CREATE TABLE INT_PACKAGE (
  ID BIGINT PRIMARY KEY AUTOINCREMENT,
  NAME VARCHAR (32) NOT NULL
);

CREATE TABLE INT_ACTION (
  ID BIGINT PRIMARY KEY AUTOINCREMENT,
  NAME VARCHAR (32) NOT NULL
);

CREATE TABLE PACKAGE_ACTION_MAPPING (
  ID BIGINT PRIMARY KEY AUTOINCREMENT,
  PACKAGE_ID BIGINT REFERENCES INT_PACKAGE(ID),
  ACTION_ID BIGINT REFERENCES INT_ACTION(ID)
);

Java 中的实体 class:

@Entity
@Table(name = "INT_PACKAGE")
public class IntPackage {
    @Id
    private Long id;
    private String name;

    @ManyToMany(cascade = { CascadeType.ALL })
    @JoinTable(name = "PACKAGE_ACTION_MAPPING", joinColumns = {
            @JoinColumn(name = "PACKAGE_ID") }, inverseJoinColumns = { @JoinColumn(name = "ACTION_ID") })
    @OrderBy("ID ASC")
    private List<IntAction> actions;

    //getters setters
}


@Entity
@Table(name = "INT_ACTION")
public class IntAction {
    @Id
    private Long id;
    private String name;

    @JsonIgnore
    @ManyToMany(mappedBy = "actions")
    private List<IntPackage> intPackage;

    //getter setters
}

请提出一些实现方法。

我建议您使用 SortedSet 而不是在数据库上排序,并使 class 具有可比性。

@Entity
@Table(name = "INT_PACKAGE")
public class IntPackage {
    @Id
    private Long id;
    private String name;

    @ManyToMany(cascade = { CascadeType.ALL })
    @JoinTable(name = "PACKAGE_ACTION_MAPPING", joinColumns = {
            @JoinColumn(name = "PACKAGE_ID") }, inverseJoinColumns = { @JoinColumn(name = "ACTION_ID") })
    private SortedSet<IntAction> actions;

    //getters setters
}


@Entity
@Table(name = "INT_ACTION")
public class IntAction implements Comparable<IntAction> {
    @Id
    private Long id;
    private String name;

    @JsonIgnore
    @ManyToMany(mappedBy = "actions")
    private List<IntPackage> intPackage;

    //getter setters

    public int compareTo(IntAction other) {
        return Integer.compare(id, other.id);
    }
}