Hibernate查询多对多映射

时间:2017-01-19 11:40:23

标签: java mysql hibernate

我一直在使用多对多的映射,这是我的POJO类。

Menu.java:

@Entity
@Table(name = "menu")
public class Menu {

    @Id
    @Column(name = "menuid")
    @GeneratedValue
    private int menuid;

    @Column(name = "parentid")
    private int parentid;

    @Column(name = "menuname")
    private String menuname;

    @Column(name = "url")
    private String url;

    @Column(name = "status")
    private String status;

    @Column(name = "usertype")
    private String usertype;

    @Column(name = "isparent")
    private boolean isParent;
    private ArrayList<Menu> childMenu;

    @ManyToMany(mappedBy="menus")                                       
    private List<User> users;

    public Menu(Integer menuid){
        this.menuid=menuid;
    }

    public Menu(){
    }

User.java:

@Entity
@Table(name = "user")
public class User implements Serializable {

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

    @Column(name = "OUTLET_ID")
    private int outletId;

    @Column(name = "NAME")
    private String name;

    @Column(name = "USERTYPE")
    private String userType;

    @Column(name = "LOGINID")
    private String loginId;

    @Column(name = "PASSWORD")
    private String password;

    @Column(name = "CREATEDDATE")
    private String createdDate;

    @Column(name = "CONTACTNUMBER")
    private String contactNumber;

    @Column(name = "EMAILID")
    private String emailId;

    @Column(name = "OUTLETTYPE")
    private String outlettype; 

    @Transient
    private String nsec;

    @javax.persistence.Transient
    ArrayList<Integer> menuid;

    @javax.persistence.Transient
    ArrayList<Long> clientid;

    @javax.persistence.Transient
    ArrayList<String> clientName;

    @ManyToMany(fetch=FetchType.EAGER) @JsonIgnore
    @JoinTable(name="user_menu",joinColumns={@JoinColumn(name="userid")},
                                                    inverseJoinColumns={@JoinColumn(name="menuid")})
    public List<Menu> menus;

    @ManyToMany(fetch=FetchType.EAGER) @JsonIgnore
    @JoinTable(name="user_client",joinColumns={@JoinColumn(name="userid")},
                                                    inverseJoinColumns={@JoinColumn(name="outletid")})

    public List<Client> clients;

    public User() { 
    }

我有自动创建的用户,菜单和第三个映射表user_menu,我在mysql中查询后成功获取结果

select * from menu m inner join user_menu um on m.menuid = um.menuid where um.userid = 41;

我想在hibernate中写这个查询怎么样这个东西???

1 个答案:

答案 0 :(得分:0)

最后我找到了答案,这是我的hql查询,

    SELECT count(DISTINCT(idmovie)) FROM screening INTO @number_of_movies;