如何在模型中建立一个反身的一对多关系?

时间:2017-03-20 15:14:11

标签: java jpa

在数据库中有一个表具有反身的一对多关系:

create table structure 
(
   struct_code          varchar2(15)         not null,
   str_struct_code      varchar2(15),
   struct_lib           varchar2(255),
   struct_sigle         varchar2(10),
   struct_comment       clob,
   struct_interne       smallint             default 1,
   constraint pk_structure primary key (struct_code)
);

alter table structure add constraint fk_structur_associati_structur foreign key (str_struct_code) references structure (struct_code);

我创建了相应的模型:

@Entity
@Table(name = "structure")
public class Structure {

    @Id()
    @Column(name="struct_code") 
    private String code;

    @Column(name="struct_sigle")
    private String sigle;

    @Column(name="struct_lib")
    private String lib;

    @Column(name="struct_interne")
    private Integer interne;

    @ManyToOne
    @JoinColumn(name = "struct_code")
    private Structure sousStructure;

    public Structure() {
        super();
    }

    public Structure(String code) {
        super();
    }

    // getters and setters

}

但是当我构建项目时,我收到错误:mappingexception repeated column in mapping for entity : com.ambre.pta.model.Structure column: struct_code (should be mapped with insert="false" update="false")

那么如何正确地写出反身关系?

1 个答案:

答案 0 :(得分:0)

我确实有这样的事情:

@ManyToOne
@JoinColumn(name = "parent_struct_code", nullable = true)
private Structure parentStructure;

@OneToMany(mappedBy = "parentStructure", cascade = CascadeType.REMOVE, fetch=FetchType.LAZY)
private List<Structure> sousStructures = new ArrayList<>();