Home Hibernate mapping entity with a Set of itself
Reply: 1

Hibernate mapping entity with a Set of itself

LSikh
1#
LSikh Published in 2018-01-11 12:54:41Z

I have this class in my code

@Entity(name = "Point")
@Table(name = "Point")
public class Point extends com.lsikh.unlmaps.base.Entity<Integer>{
    private Integer id;
    ...
    ...
    private Set<Point> connections = new HashSet<Point >();

I need to relate a Point entity with many other Point's object in that Set and retrieve.

This are my tables in the database

  CREATE
    TABLE Point(
        id INTEGER UNIQUE AUTO_INCREMENT NOT NULL,
        ...
        ...
        PRIMARY KEY (id )
    );

CREATE
    TABLE Connections(
        idA INTEGER NOT NULL,
        idB INTEGER NOT NULL,
        FOREIGN KEY (idA ) REFERENCES Point (id),
        FOREIGN KEY (idB ) REFERENCES Point(id)
    );

Which is the correct set of hibernate notations to do this. I think could be

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "Connections", joinColumns = { 
            @JoinColumn(name = "id") }, inverseJoinColumns = { 
                    @JoinColumn(name = "idA") })
    public Set<Point> getConnections() {
        return connections;
    }

But I'm having problems to do the map and I'm not sure.

Maciej Kowalski
2#
Maciej Kowalski Reply to 2018-01-11 13:01:54Z

According to the javadoc the joinColumns:

The foreign key columns of the join table which reference the primary table of the entity owning the association

So assuming that idA is the id of the owning entity in the join table the mapping should be:

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "Connections", joinColumns = { 
        @JoinColumn(name = "idA") }, inverseJoinColumns = { 
                @JoinColumn(name = "idB") })
public Set<Point> getConnections() {
    return connections;
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.296578 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO