使用休眠使用联接的SQL查询

时间:2018-09-16 21:21:43

标签: java hibernate jpa java-ee

在我的项目中,我创建了此类:

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

谁提供了这张表:

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

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

我想搜索关注者。使用SQL查询,它将给出:

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

我想做一个这样的班级追随者:

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

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

但是我有一个错误:

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

1 个答案:

答案 0 :(得分:0)

您需要进行双向映射,因为Wall_follower具有多对多关系。

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

此外,按如下所示在wall类中更改映射

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