我有以下需要解决的问题。
核心问题是我想向JPA中的ManyToMany关系的JoinTable中添加其他列。就我而言,我有以下实体。

主题是具有许多RemoteDocument的简单实体(一个RemoteDocument可以由许多Topic引用,因此应该是ManyToMany关系)。此外,RemoteDocument实体也是只读的,因为它可能只能从Oracle实体化 View 中读取,而且禁止对该实体化 View 进行任何更改。所以我想存储与某些主题相关的RemoteDocuments的顺序。实际上,我可以使用其他实体来做类似的事情:

@Entity
public class Topic {
 @Id
 private Long id;
 @Basic
 private String name;

    @OneToMany
 private Set<TopicToRemoteDocument> association;
}

@Entity
public class RemoteDocument {
 @Id
 private Long id;
 @Basic
 private String description;
}

@Entity
public class TopicToRemoteDocument {
 @OneToOne
 private Topic topic;
 @OneToOne
 private RemoteDocument remoteDocument;
 @Basic
 private Integer order;
}

在这种情况下,其他实体TopicToRemoteDocument可帮助我将OneToMany关联替换为ManyToMany关联,并添加额外的字段顺序。

但是我想拥有ManyToMany关系,但在联接表中配置了其他列

最佳答案

使用list而不是set,连同@OrderColumn批注和JPA一起自动处理订单:

@MappedSuperclass
public class BaseEntity{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    public Long getId(){
        return id;
    }

    public void setId(final Long id){
        this.id = id;
    }

}

@Entity
public class Topic extends BaseEntity{

    @ManyToMany(mappedBy = "topics")
    @OrderColumn
    private List<Document> documents = new ArrayList<Document>();

    public List<Document> getDocuments(){
        return documents;
    }

    public void setDocuments(final List<Document> documents){
        this.documents = documents;
    }

}

@Entity
public class Document extends BaseEntity{

    @ManyToMany
    @OrderColumn
    private List<Topic> topics = new ArrayList<Topic>();

    public List<Topic> getTopics(){
        return topics;
    }

    public void setTopics(final List<Topic> topics){
        this.topics = topics;
    }

}

生成的DDL(使用 hibernate 和HSQL):
create table Document (
    id bigint generated by default as identity (start with 1),
    primary key (id)
);

create table Document_Topic (
    documents_id bigint not null,
    topics_id bigint not null,
    topics_ORDER integer not null,
    documents_ORDER integer not null,
    primary key (documents_id, topics_ORDER)
);

create table Topic (
    id bigint generated by default as identity (start with 1),
    primary key (id)
);

alter table Document_Topic
    add constraint FK343B5D0B481100B2
    foreign key (documents_id)
    references Document;

alter table Document_Topic
    add constraint FK343B5D0B558627D0
    foreign key (topics_id)
    references Topic;

10-04 20:09