简体   繁体   中英

sql query with join using hibernate

in my project I created this class:

@Entity
@Table(name= "Wall")
public class Wall {

    @Id
    @GeneratedValue
    @Column(name="id")
    private Integer id;

    @ManyToOne
    @JoinColumn(name="user_id", nullable=false)
    private User user;

    @ManyToOne
    @JoinColumn(name="likable_id", nullable=false)
    private Likable likable;

    @ManyToMany(cascade = { CascadeType.ALL })
    @JoinTable(
        name= "Wall_Follower",
        joinColumns = { @JoinColumn(name = "wall_id") },
        inverseJoinColumns = { @JoinColumn(name = "follower_id") }
    )
    private Set<User> followers;

who gives this tables:

Wall
+----+------------+---------+
| id | likable_id | user_id |
+----+------------+---------+

Wall_Follower
+---------+-------------+
| wall_id | follower_id |
+---------+-------------+

And I would like to search the followers. With an SQL query it would give:

SELECT * FROM `Wall_Follower` AS MF 
    LEFT JOIN `Wall` AS M 
    ON MF.wall_id= M.wall_id 
    WHERE MF.follower_id = 1

I thought of doing a class Follower like this:

@Entity
@Table(name= "Mur_Follower")
public class Follower {

    @Id
    @Column(name="follower_id")
    private Integer id;
    @Column(name="mur_id")
    private Mur mur;

but I have an error:

Could not determine type for: beans.Wall, at table: Wall_Follower, for columns: [org.hibernate.mapping.Column(wall_id)]

You need to have bidirectional mapping as Wall_follower is having many to many relationship.

@Entity
@Table(name= "Mur_Follower")
public class Follower {

    @Id
    @Column(name="follower_id")
    private Integer id;
    @Column(name="mur_id")
    private Mur mur;

 @ManyToMany(cascade = { CascadeType.ALL })
    @JoinTable(
        name= "Wall_Follower",
        joinColumns = { @JoinColumn(name = "follower_id") },
        inverseJoinColumns = { @JoinColumn(name = "wall_id") }
    )
    private Set<Wall> walls;

Also, change your mapping in wall class as follows

 @ManyToMany(cascade = { CascadeType.ALL })
    @JoinTable(
        name= "Wall_Follower",
        joinColumns = { @JoinColumn(name = "wall_id") },
        inverseJoinColumns = { @JoinColumn(name = "follower_id") }
    )
    private Set<Follower> followers;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM