pheromix
pheromix

Reputation: 19347

How to make a reflexive one-to-many relationship inside a model?

In the database there is a table having a reflexive one-to-many relationship :

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);

I created the corresponding model :

@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

}

But when I built the project then I got the error : mappingexception repeated column in mapping for entity : com.ambre.pta.model.Structure column: struct_code (should be mapped with insert="false" update="false")

So how to write correctly the reflexive relation ?

Upvotes: 0

Views: 1815

Answers (1)

KLHauser
KLHauser

Reputation: 876

I do have something like this in place:

@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<>();

Upvotes: 1

Related Questions