Search code examples
javahibernatejpahibernate-mapping

Prevent creation of foreign keys in mapping tables?


How do we prevent the creation of foreign keys in hibernate ? I need to insert some childs into my "oneToMany" relationship which do not exist yet. Hibernate should just ignore the fact that the childs do not exist yet.

Currently i receive a foreign key exception once i try to insert those non existing childs. So i need to disable the foreign key creation/useage.

@Entity
@Table(name = "chunk", uniqueConstraints = {@UniqueConstraint(columnNames={"x", "y"})}, indexes = {@Index(columnList = "x,y")})
@Access(value = AccessType.FIELD)
@SelectBeforeUpdate(false)
public class Chunk extends HibernateComponent{

    public int x;
    public int y;
    public Date createdOn;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @Fetch(FetchMode.JOIN)
    @BatchSize(size = 50)
    public Set<Identity> inChunk = new LinkedHashSet<>();

    @Transient
    public Set<ChunkLoader> loadedBy = new LinkedHashSet<>();

    public Chunk() {}
    public Chunk(int x, int y, Date createdOn) {
        this.x = x;
        this.y = y;
        this.createdOn = createdOn;
    }
}

How do we achieve this ?


Solution

  • I found an solution... instead of letting hibernate create the join table completly by yourself you can modify the creation with "JoinTable".

    @Entity
    @Table(name = "chunk", uniqueConstraints = {@UniqueConstraint(columnNames={"x", "y"})}, indexes = {@Index(columnList = "x,y")})
    @Access(value = AccessType.FIELD)
    @SelectBeforeUpdate(false)
    public class Chunk extends HibernateComponent{
    
        public int x;
        public int y;
        public Date createdOn;
    
        @OneToMany(fetch = FetchType.EAGER, cascade = {})
        @JoinTable(name = "chunk_identity", joinColumns = @JoinColumn(name = "identity_id"), inverseJoinColumns = @JoinColumn(name = "id"), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
        @Fetch(FetchMode.JOIN)
        @BatchSize(size = 50)
        public Set<Identity> inChunk = new LinkedHashSet<>();
    
        @Transient
        public Set<ChunkLoader> loadedBy = new LinkedHashSet<>();
    
        public Chunk() {}
        public Chunk(int x, int y, Date createdOn) {
            this.x = x;
            this.y = y;
            this.createdOn = createdOn;
        }
    }
    

    This way we can define if we need an foreign key or if we can simply ignore it.